Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

235
Vistas
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)
    })
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

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)
    })
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda