skip to Main Content

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


  1. You can access the current status value from within its setter function, like so:

    const interval = setInterval(() => {
      setTime(new Date());
      setStatus(currentStatus => {
        if (currentStatus != '2' && currentStatus != '0') {
          handleClickRefresh();
        }
        return currentStatus;
      }
    }, 5000);
    

    There might be a more elegant approach, but this will work too.

    Login or Signup to reply.
  2. The problem is that you missing the status as a dependency in useEffect.

    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);
    }, [status]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search