@atomico/store
@atomico/store a more predictable and natural model for asynchrony when controlling states.
GitHub - atomicojs/store
GitHub

@atomico/store is Naturally asynchronous.

1
interface State {
2
api: string;
3
loading: boolean;
4
products: { id: number; title: string; price: number };
5
}
6
7
const initialState = (state: State) => ({
8
api: "",
9
loading: false,
10
products: [],
11
});
12
13
async function* getProducts(state: State) {
14
yield { ...state, loading: true };
15
return {
16
...(yield),
17
loading: false,
18
products: await (await fetch(state.api)).json(),
19
};
20
}
21
22
const store = new Store(initialState, {
23
actions: { getProducts },
24
});
Copied!

Objectives

  1. 1.
    Asynchrony management.
  2. 2.
    Finitely predictable asynchrony.
  3. 3.
    Modularity and composition.

Asynchrony management

Application events and service calls are naturally asynchronous, with @atomico/store you can use asynchronous functions or asynchronous generators to define the update cycle.
update cycle? By this I mean the states that occur sequentially when dispatching the action, example:
1
async function* getProducts(state: State) {
2
yield { ...state, loading: true };
3
return {
4
...(yield),
5
loading: false,
6
products: await (await fetch(state.api)).json(),
7
};
8
}
Copied!
The previous action will generate 2 states when dispatched:
  1. 1.
    state 1:{loading: true, products:[]}
  2. 2.
    state 2: {loading: false, products:[...product]}
The advantage of this is that the process is clearly observable by the store and by whoever dispatches the action.

Finitely predictable asynchrony

Every action in @atomico/store is wrapped in a promise that defines when it ends its cycle, this will let you execute actions sequentially, example:
1
await store.actions.orderyBy();
2
await store.actions.insert({ id: 1000 });
3
await store.actions.updateAll();
Copied!

Modularity and composition

@atomico/store allows to decouple the actions and the state of the store, for a better modularization , example:
actions.js
store.js
1
export interface State {
2
api: string;
3
loading: boolean;
4
products: { id: number; title: string; price: number };
5
}
6
7
export const initialState = (state: State) => ({
8
api: "",
9
loading: false,
10
products: [],
11
});
12
13
export async function* getProducts(state: State) {
14
yield { ...state, loading: true };
15
return {
16
...(yield),
17
loading: false,
18
products: await (await fetch(state.api)).json(),
19
};
20
}
Copied!
1
import * as Actions from "./actions";
2
3
export default new Store(Actions.initialStore, { actions: { Actions } });
Copied!

Api

Last modified 2mo ago