Skip to content

Instantly share code, notes, and snippets.

@narennaik
Created May 27, 2021 07:40
Show Gist options
  • Save narennaik/726df6f56b3e199fe05c91b756b51328 to your computer and use it in GitHub Desktop.
Save narennaik/726df6f56b3e199fe05c91b756b51328 to your computer and use it in GitHub Desktop.
create store
const store = (reducer) => {
let state = []; // Can be an object as well
let listeners = [];
const dispatch = (action) => {
state = reducer(state, action);
listeners.forEach((listener) => listener(state));
};
const subscribe = (listener) => {
listeners.push(listener);
return () => {
// To unsubscribe
listeners.filter((l) => l !== listener);
};
};
return { state, dispatch, subscribe };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment