From e880c94afaf53db6c2a4a5491005cfcc3c0a6dc3 Mon Sep 17 00:00:00 2001 From: cha0s Date: Tue, 23 Mar 2021 13:42:52 -0500 Subject: [PATCH] refactor: hooks --- packages/react/src/hooks/use-event.js | 15 +++++++++++++++ packages/react/src/index.js | 1 + 2 files changed, 16 insertions(+) create mode 100644 packages/react/src/hooks/use-event.js diff --git a/packages/react/src/hooks/use-event.js b/packages/react/src/hooks/use-event.js new file mode 100644 index 0000000..328d59e --- /dev/null +++ b/packages/react/src/hooks/use-event.js @@ -0,0 +1,15 @@ +import {useEffect} from 'react'; + +export default function useEvent(object, eventName, fn) { + useEffect(() => { + if (!object) { + return undefined; + } + const onEvent = (...args) => { + fn(...args); + }; + onEvent(); + object.on(eventName, onEvent); + return () => object.off(eventName, onEvent); + }, [eventName, fn, object]); +} diff --git a/packages/react/src/index.js b/packages/react/src/index.js index 9e91443..9902bf9 100644 --- a/packages/react/src/index.js +++ b/packages/react/src/index.js @@ -5,6 +5,7 @@ export {default as PropTypes} from 'prop-types'; // eslint-disable-next-line import/no-extraneous-dependencies export {LatusContext} from '@latus/react/client'; +export {default as useEvent} from './hooks/use-event'; export {default as useLatus} from './hooks/use-latus'; export {default as usePrevious} from './hooks/use-previous';