Gass
Gass

Reputation: 9344

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)
    })
}

Upvotes: 1

Views: 76

Answers (1)

MWO
MWO

Reputation: 2806

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)
    })
}

Upvotes: 1

Related Questions