Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

clearing an setInterval in react by using a loading state

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading