Entity Store

Last updated 21 days ago

For the most part, the stores you'll require in your applications will be entity stores.

You can think of an entity store as a table in a database, where each table represents a flat collection of entities.

Akita's EntityStore simplifies the process, giving you everything you need to manage it.

Let's see how we can use it to create a todos table, i.e., an EntityStore managing a Todo object:

import { Todo } from './todo.model';
import { EntityState, EntityStore, StoreConfig } from '@datorama/akita';
export interface TodosState extends EntityState<Todo> { }
@StoreConfig({ name: 'todos' })
export class TodosStore extends EntityStore<TodosState, Todo> {
constructor() {
super();
}
}

First, we need to define the store's interface. In our case, we can make do with extending the EntityState from Akita, providing it with the Todo Entity type.

EntityState has the following signature:

export interface EntityState<T> {
entities: HashMap<T>;
ids: ID[];
loading: boolean;
error: any;
}

By using this model, you will receive a lot of built-in functionality from Akita. Let's explore them in the next section.

Extend the Entity Store

Sometimes it's useful to extend the store and add more properties to it, for example, you might want to save the todos active filter.

First, we need to add the property type:

export interface TodosState extends EntityState<Todo> {
filter: string;
}

Next, we need to pass the initial state in the constructor:

@StoreConfig({ name: 'todos' })
export class TodosStore extends EntityStore<TodosState, Todo> {
constructor() {
super({ filter: 'ALL' });
}
}

Now, we'll get the following state:

{
entities: HashMap<T>;
ids: ID[];
loading: boolean;
error: any;
filter: string; <====
}

To update extended properties, you can use the update() method. For example:

todos.service.ts
class TodosService {
updateFilter(filter) {
this.todosStore.update({
filter: 'COMPLETED'
});
}
}