import noop from "lodash/noop"; import { useCallback, useEffect, useRef } from "react"; import { FetchKey, HttpMethod } from "./types"; import { useFetchContext } from "./useFetchContext"; export function useFetchSubscribe( key: FetchKey | undefined, handle: (method: HttpMethod, data?: any) => void, deps?: any[], ): VoidFunction { const unsubscriber = useRef(noop); const fetchContext = useFetchContext(); useEffect(() => { if (!fetchContext || !key) { return; } let isEffectRunning = true; const unsubscribe = fetchContext.subscribe?.(key, handle); unsubscriber.current = () => { if (isEffectRunning) { isEffectRunning = false; unsubscribe?.(); } }; return () => { isEffectRunning = false; unsubscribe?.(); } }, [key, handle, fetchContext, deps]); return useCallback(() => { unsubscriber.current(); }, [unsubscriber]); };