The Store

The Store is a single object which contains the store state and serves as the "single source of truth."

To create a store, you need to extend Akita's Store, passing the type as well as its initial state.

session.store.ts
import { Store, StoreConfig } from '@datorama/akita';
export interface SessionState {
token: string;
name: string;
}
export function createInitialState(): SessionState {
return {
token: '',
name: ''
};
}
@StoreConfig({ name: 'session' })
export class SessionStore extends Store<SessionState> {
constructor() {
super(createInitialState());
}
}

With this setup you get a Store with the following methods:

Update the Store

  • update(newStateFn: Partial<S> | state: Readonly<S> => S)

When you want to update the store, you can call the update() method passing the new state:

import { SessionStore } from './session.store';
export class SessionService {
constructor(private sessionStore: SessionStore) {}
updateUserName(newName: string) {
this.sessionStore.update({ name: newName });
}
}

The second update() option gives you more control. It receives a callback function, which gets the current state, and returns a new immutable state, which will be the new value of the store. For example:

import { SessionStore } from './session.store';
export class SessionService {
constructor(private sessionStore: SessionStore) {}
updateUserName(newName: string) {
this.sessionStore.update(state => ({
name: newName
}));
}
}

Set the Loading State

  • setLoading(isLoading: boolean)

Set the Error State

Update the store's error state.

  • setError(error)

Destroy the Store

  • destroy()

If you need "safer types" when using the update method with a callback function check out the advice in this thread.