• Jobs
  • About Us
  • Jobs
    • Home
    • Jobs
    • Courses and challenges
  • Businesses
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

203
Views
How can I re-fetch an API automaticaly until data is fetched succesfully?

I have an API that sometimes doesn't work. I would like for the App to refetch automaticaly if this happens until it gets the necessary data. How can I do that? I'm thinking that maybe this could be done by using a dependency on the useEffect hook, but I'm not clear on how to do it.

Lets say we have this App component

export default function App() {
  const [data, setData] = useState([])

  useEffect(() => {
    getData({ setData })
  }, [])

   return [
    <h3>
      {data[0].title}
    </h3>
  ]
}

And this API component

const url = 'https://some-random-url.com/whatever-api'

export default function getData({ setData }) {

  axios.get(url)
    .then((response) => {
      let dataArray = response.data.results
      setData(dataArray)
    })
    .catch((error) => {
      console.log(error)
    })
}
over 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

If you were to do it with useEffect, you could pass an error counter state to getData function and increase it on error or empty data. Then add to your useEffect dependency array to refetch. But this certainly implies that you have to think further what you are wanting to do after a certain amount of retries, to avoid an infinite loop.

export default function App() {
  const [data, setData] = useState([])
  const [errCount, setErrCount] = useState(0)

  useEffect(() => {
    getData({ setData, errCount, setErrCount })
  }, [errCount])

   return [
    <h3>
      {data[0].title}
    </h3>
  ]
}

And this API component

const url = 'https://some-random-url.com/whatever-api'

export default function getData({ setData, errCount, setErrCount }) {

  axios.get(url)
    .then((response) => {
      let dataArray = response.data.results
      setData(dataArray)
      !dataArray.length && setErrCount(errCount+1); 
    })
    .catch((error) => {
      setErrCount(errCount+1); 
      console.log(error)
    })
}
over 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Show me some job opportunities
There's an error!