DEV Community

Cover image for State management in its own module in vanilla JavaScript
chovy
chovy

Posted on

State management in its own module in vanilla JavaScript

You can organize your code better by separating the state management into its own module. Here's how you might do it:

In store.js:

// Define the initial state
let state = {
  count: 0
};

// Define a list of subscribers
let subscribers = [];

// Define a function to update the state and notify subscribers
function setState(newState) {
  state = newState;

  // Notify subscribers
  for (let i = 0; i < subscribers.length; i++) {
    subscribers[i](newState);
  }
}

// Define a function to subscribe to state changes
function subscribe(callback) {
  subscribers.push(callback);
}

// Export the state, setState, and subscribe functions
export { state, setState, subscribe };
Enter fullscreen mode Exit fullscreen mode

In main.js (or wherever you want to use the state):

import { state, setState, subscribe } from './store.js';

// Subscribe a function that updates the DOM to state changes
subscribe(function(newState) {
  document.getElementById('count').textContent = "Count: " + newState.count;
});

// Define a function to increment the count
function incrementCount() {
  setState({
    count: state.count + 1
  });
}

// Call the function to increment the count
incrementCount();
Enter fullscreen mode Exit fullscreen mode

In this example, store.js exports the current state, a setState function to update the state, and a subscribe function to subscribe to state changes. Then, in main.js, you import these exports and use them to manage the state of your application.

Please note that this example uses ES6 modules, which may not be supported in all environments without a build step (like Babel or webpack). You might also need to run this code on a server (like using the http-server package in Node.js), as some browsers don't support ES6 modules with the file:// protocol, which is typically used when you open an HTML file directly in your browser.

If you're looking for a remote job working with javascript, signup for Grazily.com (it's free)

Top comments (0)