Skip to content

Instantly share code, notes, and snippets.

@victorwpbastos
Forked from henriquesosa/useGlobal.js
Created April 22, 2021 17:52
Show Gist options
  • Save victorwpbastos/6864a4d0abfe0ca462e4f2d60bcaf666 to your computer and use it in GitHub Desktop.
Save victorwpbastos/6864a4d0abfe0ca462e4f2d60bcaf666 to your computer and use it in GitHub Desktop.
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