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

204
Visualizações
JavaScript the rest of function executes before API calls

I have a problem with a simple function which where I want to call an API and then do something with the response. Basically, I just want to set my react component state to the response I get and then navigate to the other page The problem is that my code executes another part of the function before an API call is finished, and I end up on another page with console.log of undefined

There is my function:

  const startNewGame = () => {
    GameService.startGame()
      .then((response) => {
        setGame(response.data);
        console.log(game);
        navigate('intro');
      })
      .catch((e) => {
        console.log(e);
      });
  };

I can wrap my navigate into if(!game !== undefined) but then I have to click two or more times on a button.

Thank you all guys for help :)

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You probably do several things incorrect at the same time, so to understand what exactly is wrong might take some time. Take these steps to debug your code:

  1. Make each .then call do only one thing (and stick to that principle in other cases). You could chain as many .then as you like. Moreover you could return data from one .then to the next, so your code might look like this:
 GameService.startGame()
      .then(response => response.data)
      .then(data => {
        setGame(data) 
      })
      .then(() => {
        console.log(game);
        navigate('intro');
      })
      .catch((e) => {
        console.log(e);
      });

  1. Understand your components composition. Where exactly are you saving your response? is it just local component useState or some Context Api state that wraps the app? When you navigate to "other page" your "current page" state will be unavailable to "other page" unless you keep the data somewhere up in the tree when both pages could access that.

  2. For further references keep in mind that setGame is asynchronous, so you need to wait for the state to be updated to make sure that its updated.

about 4 years ago · Juan Pablo Isaza Relatório

0

Try this:

const startNewGame = () => {
  GameService.startGame()
    .then((response) => {
      setGame(response.data);
      // game is not updated yet
      // console.log(game); <- Remove this line
      // navigate('intro'); <- Remove this line
    })
    .catch((e) => {
      console.log(e);
    });
};

useEffect(()=>{
  if(game !== undefined){
    navigate('intro')
  }
}, [game])
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