DEV Community

Eddie
Eddie

Posted on

13 3

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

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

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

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay