Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
GlobalState
class GlobalState {
state = {};
listeners = [];
constructor(reducer, initialState = {}) {
this.reducer = reducer;
this.state = initialState;
this.devTools = typeof window !== 'undefined' && window?.__REDUX_DEVTOOLS_EXTENSION__?.connect();
}
listen(listener) {
this.listeners.push(listener);
}
unlisten(listener) {
this.listeners = this.listeners.filter(l => l !== listener);
}
dispatch = (actionName, payload) => {
const nextState = this.reducer(this.state, actionName, payload);
if (nextState !== this.state) {
this.state = nextState;
this.listeners.forEach(l => l(nextState));
this.devTools && this.devTools.send(actionName, payload);
}
};
}
@DominicTobias
Copy link
Author

DominicTobias commented Jan 29, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment