UNPKG

@equinor/fusion-observable

Version:
30 lines 1.19 kB
import { useLayoutEffect, useState } from 'react'; /** * Applies a side-effect to a {@link FlowSubject}. * * The subscription is created on mount (or when `subject` changes) and torn down * on unmount. Pass an action type string as the second argument to filter effects * to a single action type, or pass the effect function directly to handle all actions. * * **Important:** The effect may return a new action, which will be dispatched back * into the subject. Be careful to avoid infinite loops. * * @example * ```tsx * useObservableEffect(subject, 'fetchUser', (action, state) => { * return { type: 'setLoading', payload: true }; * }); * ``` */ export function useObservableEffect(subject, effectOrType, effect) { const [type] = useState(() => (typeof effectOrType === 'string' ? effectOrType : undefined)); const [fn] = useState(() => effect ?? effectOrType); useLayoutEffect(() => { const subscription = type ? subject.addEffect(type, fn) : subject.addEffect(fn); return () => subscription.unsubscribe(); }, [subject, type, fn]); } export default useObservableEffect; //# sourceMappingURL=useObservableEffect.js.map