UNPKG

@barguide/react-hooks

Version:
35 lines (27 loc) 807 B
import { useEffect, useState } from 'react'; import { emitter } from './utils'; /** * @name useCheckoutLoader * @description We use the "effect" hook to add/remove an "emitter" instance * to our Modal component. By passing the "setter" from our React State we * can get a live subscription to the state state */ const useEmitter = ( event: string, callback?: any, initialValue: any = false ) => { const [state, setState] = useState(initialValue); const onEventCallback = (value = !state) => { setState(value); if (typeof callback === 'function') callback(value); }; useEffect(() => { emitter.addListener(event, onEventCallback); return () => { emitter.removeListener(event, onEventCallback); }; }); return [state, setState]; }; export { useEmitter };