'useinterval in react (polling request)

I've created a simple react (nextjs) app that sends some data to a backend server. While the data are being processed the react app keeps track of the progression through multiple polling requests which are launched thanks to the setInterval function. See below:


import {badPolling, goodPolling} from './somewhere/in/my/computer'
import { useState } from "react"

const MyComponent = () => {
  const [msg, setMsg] = useState(null)
  const [data, setData] = useState(null)
  const [progress, setProgress] = useState(0)

  const processData = async () => {

    const res = await startProcess() //axios post request
    const {id, success} = res
    if(success){

      let isPolling = false

      const intervalId = setInterval(() =>{
        if(isPolling) return //Wait the current request to finish

        polling(id) //Axios polling request
          .then(r => {
            const { progression, finished, success} = r

            if(!success){
              badPolling(id) //axios get request
                .then(() => setMsg('Something went wrong'))
                .catch(() => setMsg('Something went wrong'))
              clearInterval(intervalId)
              setProgress(null)
            }else if(finished){
              goodPolling(id) // axios get request
                .then(r => setData(r.data))
                .catch(() => setMsg('Something went wrong'))
              clearInterval(intervalId)
              setProgress(null)
            }else{
              setProgress(progression)
            }

          })

          isPolling = false

      })

    }else{
      setMsg('Something went wrong')
      setProgress(null)
    }

  }

  return (
    <div>
      <button onClick={processData}></button>
      <div>{msg}</div>
      <div>Progress: {progress}</div>
    </div>
  )
}

export default MyComponent

The problem is that once the process is finished due to an error the client app keeps sending several "badPolling" requests until it stops. Moreover it seems that at the end of the process my states are changed one last time without me doing it.

Thanks



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source