Skip to content

Instantly share code, notes, and snippets.

@narennaik
Last active August 1, 2021 09:12
Show Gist options
  • Save narennaik/f8eb4992790113ba08f7265d87419546 to your computer and use it in GitHub Desktop.
Save narennaik/f8eb4992790113ba08f7265d87419546 to your computer and use it in GitHub Desktop.
How do we know when the state changes? We subscribe!
const state = {};
const listeners = [];
const subscribe = (listener) => {
listeners.push(listener);
};
const dispatch = (action/change) => {
const newState = getNewState(state, action);
state = newState;
listeners.forEach(listener => {
listener(state)
});
};
const action = { type: 'ADD_TODO', change: 'Go to the cafe' };
dispatch(action)
const listener = (newState) => {
// Do something after knowing the change
};
subscribe(listener);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment