Blog>
Snippets

Performing Akita Actions to Update State

Display how to define and dispatch actions in Akita to update the state of the store based on events triggered in Angular components.
import { Injectable } from '@angular/core';
import { Store, StoreConfig } from '@datorama/akita';

export interface SessionState {
   token: string | null;
}

export function createInitialState(): SessionState {
   return {
       token: null
   };
}

@Injectable({ providedIn: 'root' })
@StoreConfig({ name: 'session' })
export class SessionStore extends Store<SessionState> {
   constructor() {
       super(createInitialState());
   }
}
Defines a store for session state using Akita. The store has a 'token' property.
import { Injectable } from '@angular/core';
import { SessionStore } from './session.store';

@Injectable({ providedIn: 'root' })
export class SessionService {
   constructor(private sessionStore: SessionStore) {}

   updateToken(newToken: string) {
       this.sessionStore.update(state => ({
           ...state,
           token: newToken
       }));
   }
}
Creates a service that includes a method to update the token in the session store.
import { Component } from '@angular/core';
import { SessionService } from '../state/session.service';

@Component({
   selector: 'app-login',
   template: `<button (click)="login()">Login</button>`
})
export class LoginComponent {
   constructor(private sessionService: SessionService) {}

   login() {
       // Here you would typically call an auth service to login
       const fakeToken = '12345'; // Example token
       this.sessionService.updateToken(fakeToken);
   }
}
Implements an Angular component with a Login button that calls the updateToken method from the SessionService when clicked.