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

206
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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