Skip to content

Instantly share code, notes, and snippets.

@andregardi
Created April 8, 2019 02:40
Show Gist options
  • Select an option

  • Save andregardi/ff77857b04cde207cd67bb09861c4086 to your computer and use it in GitHub Desktop.

Select an option

Save andregardi/ff77857b04cde207cd67bb09861c4086 to your computer and use it in GitHub Desktop.
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