session-store
A data persistence layer for a react/next-app.
It can be also used for state-management (see examples/todo-app)
Example usage
1) Using javascript
a) Define and initialize your store
class UserStore extends SessionStore {
constructor() {
super();
this.users = [];
}
get users() {
return this.getData("_users");
}
set users(users: Array<IUser>) {
this.setData("_users", users);
}
async init() {
await super.init();
}
destroy() {
}
}
export new UserStore();
b) In your root page component, handle store lifecycle
4) Handle store lifecycle
useEffect(() => {
UserStore.init();
return () => {
UserStore.destroy();
}
}, []);
Summary of what is happenning?
- Define your store
** BaseSessionStore - data persistence with session storage
** BaseLocalStore - data persistence with local storage
- Add data getters and setters for your store.
- Initialize all data in the constructor
- Lifecycle
** (optional) Put all your startup logic in the init block.
** (optional) Put all your cleanup logic in the destroy block.
2) Example usage using typescript
a) Define your data
interface IUser {
name: string;
email: string;
age: number;
gender: string;
}
b) Create your store class and inherit SessionStore like below
class UserStore extends SessionStore<IUser> {
}
Rest of the steps are same with javascript usage.
Advanced usage
-
- name of your store
-
- handle store dependencies
-
- isReady - flag to indicate your store has been initialized from data persistence layer (e.g.-> data is loaded from session storage / local storage)
-
- isStoreReady - flag to indicate that the store has been initialized (from init block) and it is ready for serving data to its consumers (other stores/componenets etc.)
class UserStore extends SessionStore {
constructor() {
super("name_of_your_store", );
this.users = [];
}
}
export new UserStore(Store1, Store2);