I would like to refresh a component every 5 seconds, but when I hit a stop condition I stop the rerender.
The actual code is:
const [status,setStatus ] = useState(''); //0:failed, 1:waiting, 2:success
useEffect(() => {
const interval = setInterval(() => {
setTime(new Date());
if(status!='2' && status!='0'){ //if succes or fail STOP CALLING THE API
handleClickRefresh()
}
}, 5000);
return () => clearInterval(interval);
}, []);
const handleClickRefresh = async () => {
axios.get('...', {
headers: {
...
}
}).then((res) =>{
if(res.status==202){
setStatus('1'); //waiting
}else if(res.status==200){
setStatus('2'); //success
}
}).catch(
function (error) {
setStatus('0'); //fail
}
);
}
The problem seems to be that I can’t read "status" correctly, because when the component refresh status comes back to be == ''
it resets to starting value.
How can I solve the problem?
2
Answers
You can access the current
status
value from within its setter function, like so:There might be a more elegant approach, but this will work too.
The problem is that you missing the
status
as a dependency inuseEffect
.