You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
35 lines
942 B
35 lines
942 B
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<VoidFunction>(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]);
|
|
};
|
|
|