ahooks
Version:
react hooks library
43 lines (42 loc) • 1.17 kB
JavaScript
import { useRef } from 'react';
import useUpdateEffect from '../../../useUpdateEffect';
// support refreshDeps & ready
const useAutoRunPlugin = (fetchInstance, { manual, ready = true, defaultParams = [], refreshDeps = [], refreshDepsAction }) => {
const hasAutoRun = useRef(false);
hasAutoRun.current = false;
useUpdateEffect(() => {
if (!manual && ready) {
hasAutoRun.current = true;
fetchInstance.run(...defaultParams);
}
}, [ready]);
useUpdateEffect(() => {
if (hasAutoRun.current) {
return;
}
if (!manual) {
hasAutoRun.current = true;
if (refreshDepsAction) {
refreshDepsAction();
}
else {
fetchInstance.refresh();
}
}
}, [...refreshDeps]);
return {
onBefore: () => {
if (!ready) {
return {
stopNow: true,
};
}
},
};
};
useAutoRunPlugin.onInit = ({ ready = true, manual }) => {
return {
loading: !manual && ready,
};
};
export default useAutoRunPlugin;