Created
April 16, 2021 19:40
-
-
Save gustavoguichard/23cf4c71c8d3f9e3aac57174da781ec6 to your computer and use it in GitHub Desktop.
Global state
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
import { useState, useEffect } from 'react' | |
function setState(newState, updateContext) { | |
this.state = { ...this.state, ...newState } | |
this.listeners && | |
this.listeners.forEach(([context, listener]) => { | |
updateContext === context && listener(this.state) | |
}) | |
} | |
function useCustom(context) { | |
const [, newListener] = useState() | |
useEffect(() => { | |
this.listeners && this.listeners.push([context, newListener]) | |
return () => { | |
this.listeners = this.listeners | |
? this.listeners.filter(([, listener]) => listener !== newListener) | |
: [] | |
} | |
}, [newListener, context]) | |
return [this.state, this.actions] | |
} | |
function associateActions(store, actions) { | |
const associatedActions = {} | |
actions.forEach((value, key) => { | |
if (typeof value === 'function') { | |
associatedActions[key] = value.bind(null, store) | |
} | |
if (typeof value === 'object') { | |
associatedActions[key] = associateActions(store, value) | |
} | |
}) | |
return associatedActions | |
} | |
export default (actions, initialState = {}) => { | |
if (!actions) { | |
throw new Error('You need to set up some actions') | |
} | |
const store = { | |
state: initialState, | |
listeners: [], | |
setState: () => null, | |
} | |
store.setState = setState.bind(store) | |
store.actions = associateActions(store, actions) | |
return useCustom.bind(store) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
Usage in a component