Last active
January 29, 2020 15:22
-
-
Save dominictobias/8cc5de54e530ce306199ed8e89b2d8cd to your computer and use it in GitHub Desktop.
GlobalState
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | |
| } | |
| }; | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Part of https://medium.com/@dominictobias/using-react-hooks-for-global-redux-stores-97c092afe210 article