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

193
Visualizações
How to send a GET request with SetTimeout and get data if it is not ready yet?

On Submit click I send a POST request with some data to the server and in response I get an object with id and timeout. Then I need set timeout and when time comes send a GET request for the data. The problem is that data is not ready yet and I get undefined and my React app crashes.

I was told that timeout should be from the first request only (I mean I can't mannualy increase it or do something like this: timeout * 2, I need to use timeout from the first request only). How can I do that? I think it can be done somehow with While loop ...but I'm not smart enough to write this code. Please help

const [someData, setSomeData] = useState({}) // here comes undefined and app crashes because this object renders in DOM

const getData = async (id) => {
  const response = await fetch(`$BASE_URL/${id}`)
  setSomeData(response)
}

const onSubmit = async (data) => {
  const { id, timeout } = await fetch(url, data)
  
  setTimeOut(() => {
    getData(id) // data is not ready and I get undefined
  }, timeout) // its around 1000ms and I can't change it mannually
  
}

If I do this then everything works fine

const getData = async (id) => {
  const response = await fetch(`$BASE_URL/${id}`)
  setSomeData(response)
}

const onSubmit = async (data) => {
  const { id, timeout } = await fetch(url, data)
  
  setTimeOut(() => {
    getData(id) 
  }, 6000) // if I manually specify timeout to 6000
  
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

fetch will return a promises, you could use then to getData.

const onSubmit = async (data) => {
    fetch(url, data)
      .then(res => return res.json())
      .then(res => getData(res.id))
}
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