generic-data-chamber
A global data store that is library agnostic.
Installation
npm install generic-data-chamber
Importing
import { Store } from "generic-data-chamber";
Usage
1. Create a Store
import { Store } from "generic-data-chamber";
import userService from "./services/user";
import userType from "./types/user";
const store = new Store({
name: "app",
services: { user: userService },
types: { user: userType },
});
2. Create a Type
import actions from "./actions";
const user = {
name: "user",
state: {
id: null,
firstName: "",
lastName: "",
},
actions: {
getByIdAsync: {
reducer: actions.getByIdAsync,
configs: {
isPending: true,
shouldThrowErrors: false,
shouldTrackAsyncState: false,
},
},
update: actions.update,
},
};
3. Create an Action
const getByIdAsync = ({ services, prevState }, userId) => {
return services.user.getByIdAsync(userId).then((user) => {
return { ...prevState, ...user };
});
};
4. Subscribe/Unsubscribe to the Store
import appStore from "./stores/app";
const subscription = appStore.subscribe((store) => {
const { firstName, lastName } = store.getState("user");
console.log(`${firstName} ${lastName}`);
});
subscription.unsubscribe();
5. Dispatch Actions
import appStore from "./stores/app";
appStore.dispatchAsync("user.getByIdAsync", 1182);
appStore.dispatch("user.update", { firstName: "Scotty" });
6. Get Status of Async Actions
import appStore from "./stores/app";
const isPending = appStore.isPending("user.getByIdAsync");
const isError = appStore.isError("user.getByIdAsync");
const error = appStore.getError("user.getByIdAsync");