Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

241
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda