DEV Community

Eddie
Eddie

Posted on

Create your own State Management solution in one line

Not clickbait.

Create a file and name it Store.js. Put the following one line of code in it.

// Store.js
export default {};
Enter fullscreen mode Exit fullscreen mode

Now you can store any data you want and share it across your modules and components without polluting the global namespace.

Example Usage

// main.js
import Store from './Store.js';
import Settings from '../api/Settings.js';

async function init() {
  const response = await Settings.getAll();
  Store.SETTINGS = response.data; // store XHR response in Store module
}

// Module.js
import Store from './Store.js';

function getSetting(key) {
  return Store.SETTINGS[key]; // get a specific setting from the Store
}

// Task.js
import Store from './Store.js';

function loadTask(id) {
  Store.currentTaskId = id; // Store the current id in Store.js
}
Enter fullscreen mode Exit fullscreen mode

Extending the Store

How would extend this simple concept to add options for the following items?

  1. Immutability
  2. Persistence
  3. Transformation

Top comments (2)

Collapse
 
arif profile image
arif

You are using good sides of js. Using this sides with good oop knowledge makes it better

Collapse
 
maulik profile image
Maulik

totally agree with you