Created
September 14, 2020 13:30
-
-
Save pSapien/254b5fdd5efbec0e0192199db8f82593 to your computer and use it in GitHub Desktop.
Event driven approach in react
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
/** | |
*. useEvent hook | |
* | |
* @example | |
const { dispatch, on, events } = useEvents(); | |
useEffect(() => on('MyEvent', (data) => { ...do something...})); | |
*/ | |
const events = []; | |
const callbacks = {}; | |
function useForceUpdate() { | |
const [, setState] = useState(null); | |
return useCallback(() => setState({}), []); | |
} | |
function useEvents() { | |
const forceUpdate = useForceUpdate(); | |
const runCallbacks = (callbackList, data) => { | |
if (callbackList) { | |
callbackList.forEach(cb => cb(data)); | |
forceUpdate(); | |
} | |
} | |
const dispatch = (event, data) => { | |
events.push({ event, data, created: Date.now() }); | |
runCallbacks(callbacks[event], data); | |
} | |
const on = (event, cb) => { | |
if (callbacks[event]) { | |
callbacks[event].push(cb); | |
} else { | |
callbacks[event] = [cb]; | |
} | |
// Return a cleanup function to unbind event | |
return () => callbacks[event] = callbacks[event].filter(i => i !== cb); | |
} | |
return { dispatch, on, events }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment