Created
April 8, 2019 02:40
-
-
Save andregardi/ff77857b04cde207cd67bb09861c4086 to your computer and use it in GitHub Desktop.
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
| function setState(newState) { | |
| this.state = { ...this.state, ...newState }; | |
| this.listeners.forEach((listener) => { | |
| listener(this.state); | |
| }); | |
| } | |
| function useCustom(React) { | |
| const newListener = React.useState()[1]; | |
| React.useEffect(() => { | |
| this.listeners.push(newListener); | |
| return () => { | |
| this.listeners = this.listeners.filter(listener => listener !== newListener); | |
| }; | |
| }, []); | |
| return [this.state, this.actions]; | |
| } | |
| function associateActions(store, actions) { | |
| const associatedActions = {}; | |
| Object.keys(actions).forEach((key) => { | |
| if (typeof actions[key] === 'function') { | |
| associatedActions[key] = actions[key].bind(null, store); | |
| } | |
| if (typeof actions[key] === 'object') { | |
| associatedActions[key] = associateActions(store, actions[key]); | |
| } | |
| }); | |
| return associatedActions; | |
| } | |
| const useGlobalHook = (React, initialState, actions) => { | |
| const store = { state: initialState, listeners: [] }; | |
| store.setState = setState.bind(store); | |
| store.actions = associateActions(store, actions); | |
| return useCustom.bind(store, React); | |
| }; | |
| export default useGlobalHook; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment