ahooks
Version:
react hooks library
28 lines (27 loc) • 993 B
JavaScript
import { useEffect, useRef } from 'react';
import useUnmount from '../../../useUnmount';
import limit from '../utils/limit';
import subscribeFocus from '../utils/subscribeFocus';
const useRefreshOnWindowFocusPlugin = (fetchInstance, { refreshOnWindowFocus, focusTimespan = 5000 }) => {
const unsubscribeRef = useRef(undefined);
const stopSubscribe = () => {
var _a;
(_a = unsubscribeRef.current) === null || _a === void 0 ? void 0 : _a.call(unsubscribeRef);
};
useEffect(() => {
if (refreshOnWindowFocus) {
const limitRefresh = limit(fetchInstance.refresh.bind(fetchInstance), focusTimespan);
unsubscribeRef.current = subscribeFocus(() => {
limitRefresh();
});
}
return () => {
stopSubscribe();
};
}, [refreshOnWindowFocus, focusTimespan]);
useUnmount(() => {
stopSubscribe();
});
return {};
};
export default useRefreshOnWindowFocusPlugin;