Home > database >  clearing an setInterval in react by using a loading state
clearing an setInterval in react by using a loading state

Time:07-08

I am struggling with a simple timer here...I wam trying to count up when a query is running, then have it stop once the query is complete.

This is how I have currently set it up, but once the query has finished running the counter just continues to run even though !loading

  const [loading, setLoading] = useState(null)
  const [error, setError] = useState('')

  // Counter
  const [count, setCounter] = useState(0)

  const getPrestoData = async () => {
    setLoading(true)

    let count = 0

    const timer = setInterval(() => {
      count  
      setCounter(count)

      if (!loading) {
        clearInterval(timer)
      }
    }, 1000)

    await fetch(`http://127.0.0.1:8000/get-dspdaily/${dealId}`)
      .then(response => response.json())
      .then(data => {
        setData(data)
        setLoading(false)

        setDealId('')
      })
      .catch(error => {
        console.log(error)
        setError(error)
      })
  }

I have thought about putting the fetch statement inside setInterval but then it would be running every second which wouldn't be right.

I am sure this is pretty easy, but I can't figure out how to stop / pause the dam thing.

CodePudding user response:

This happens because the interval callback is using the scoped loading variable at the time the callback function was created. So it will be a constant value.

You could clear the interval in the .then or .finally block of the fetch.

But even simpler would be to remove the interval completely and just use the Performance API and get the time before and after the await.

const start = performance.now();
await fetch(`http://127.......`).then(...);
const end = performance.now();
setCounter(end - start); // in milliseconds;
  • Related