A simple Redux like data store for Vanilla JS apps
Let's create a simple data storage mechanism similar to Redux.
It's going to have the following functionalities:
Able to store data in a single JavaScript object
Persist the data in localStorage (or sessionStorage)
Allow basic CRUD operations
We'll use ES6 classes to create this re-usable ObjectStore container.
class ObjectStore {
constructor() {
this.state = {};
this.loadState();
}
}
Here, we are creating a simple state
object that will store all the data.
We are also calling the loadState()
method to load the state data upon instantiation of the object.
Let's first create a saveState()
method that will save the state object in localStorage
class ObjectStore {
...
saveState() {
localStorage.setItem("objectStore", JSON.stringify(this.state));
}
}
Now we can create a loadState()
method that will load the stored state object and set it to the current state
class ObjectStore {
...
loadState() {
const storedState = localStorage.getItem("objectStore");
if (storedState) {
this.state = JSON.parse(storedState);
}
}
}
Now coming to CRUD operations, we can start off with the Read operation and dedicate a method for it.
class ObjectStore {
...
getState() {
return this.state;
}
}
Now we can create a dispatch
method similar to redux, that takes an action
and performs certain actions corresponding to the type of action and use its payload
.
class ObjectStore {
...
dispatch(action) {
switch (action.type) {
case "ADD":
this.state = { ...this.state, ...action.payload };
break;
case "REMOVE":
const newState = { ...this.state };
delete newState[action.payload.key];
this.state = newState;
brealk;
case "UPDATE":
this.state[action.payload.key] = action.payload.value;
break;
default:
console.error("Unknown action type:", action.type);
}
this.saveState();
}
}
This pattern is similar to Redux - we use switch statements and cases to perform appropriate actions - in this case Add, Remove and Update.
This is a great little utility that can help you as a data storage mechanism for your Vanilla JS projects or if you encounter such a need during interviews.
Here's the complete code:
class ObjectStore {
constructor() {
this.state = {};
this.loadState();
}
loadState() {
const storedState = localStorage.getItem("objectStore");
if (storedState) {
this.state = JSON.parse(storedState);
}
}
saveState() {
localStorage.setItem("objectStore", JSON.stringify(this.state));
}
getState() {
return this.state;
}
dispatch(action) {
switch (action.type) {
case "ADD":
this.state = { ...this.state, ...action.payload };
break;
case "REMOVE":
const newState = { ...this.state };
delete newState[action.payload.key];
this.state = newState;
brealk;
case "UPDATE":
this.state[action.payload.key] = action.payload.value;
break;
default:
console.error("Unknown action type:", action.type);
}
this.saveState();
}
}
export default ObjectStore;