Created
March 23, 2021 15:10
-
-
Save henriquesosa/69146edb3adf249f4a74d0d1add604b2 to your computer and use it in GitHub Desktop.
This file contains 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 React from 'react'; | |
export function setState(newState) { | |
this.state = { ...this.state, ...newState }; | |
this.listeners.forEach((listener) => { | |
listener(this.state); | |
}); | |
} | |
export function useCustom() { | |
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]; | |
} | |
export function associateActions(store, actions = {}) { | |
const associatedActions = {}; | |
Object.keys(actions).forEach((key) => { | |
if (typeof actions[key] === 'function') { | |
associatedActions[key] = actions[key].bind(null, store); | |
} | |
}); | |
return associatedActions; | |
} | |
const useGlobal = (initialState, actions) => { | |
const store = { state: initialState, listeners: [] }; | |
store.setState = setState.bind(store); | |
store.actions = associateActions(store, actions); | |
return useCustom.bind(store); | |
}; | |
export default useGlobal; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment