I know that question is unusual but i need to send requests as long i don't get status finished in axios react . I am using useEffect to dispatch action get status end set status via action, useEffect dependency is set [status, dispatch, props] but still its only send 4-5 requests and stop. I also try setTimout on 500 ms but same result. Does anybody have same problem ever?
const status = useSelector((state: any) => state.reports.status);
useEffect(() => {
let timer: any = null;
if (status !== 'FINISH') {
timer = setTimeout(() => {
dispatch(getData(props.id));
}, 500);
}
return () => {
if (status === 'FINISH') {
clearTimeout(timer);
}
}
}, [ dispatch, status, props ])
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.production.min.js"></script>
CodePudding user response:
This is working for me
const [state, setState] = useState(false);
const status = useSelector((state: any) => state.reports.status);
useEffect(() => {
let timer: any = null;
if (status !== 'FINISHED') {
dispatch(getData(props.id));
// setting state after 1s or what you need
timer = setTimeout(() => {
setState(!state);
}, 1000);
}
return () => {
if (status === 'FINISHED') {
clearTimeout(timer);
}
}
}, [ status, getDataFetch, state, dispatch ])
CodePudding user response:
You have to create a state, which basically toggles the value and passe the state
to the useEffect
dependency, so the state value changes every time useEffect
is called until you don't get the status value finished
, as you can see the below code, I hope this works.
const status = useSelector((state: any) => state.reports.status);
const [state, setState] = useState(false);
useEffect(() => {
if (status !== 'FINISH') {
setState(!state);
dispatch(getData(props.id));
}
}, [ dispatch, reportStatus, props, state ])