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

214
Vistas
React useState & useEffect confusion

I have some confusion about implementing something using React functional components. I know useState is async and does not reflect the value when you read after mutating state. However I have no idea how to implement what I'm trying to do. Basically in my React component, when it mounts I ask the server for some backend information through a websocket connection and set it in state. Right after doing this I execute a method based on a switch however I can't access the state in the method yet because I have just mutated the state and because it is async the changes are not reflected directly. Here is my code:

    useEffect(() => {
      socket.emit("crash:info", (resp) => {
        const { status, gameId, gameHistory, mockVariable } = resp;
        setGameId(gameId);
        setGameHistory(gameHistory);
        setStatus(status);

        switch (status) {
          case 2:
            handleGameEnd({ variable: mockVariable });
            break;
        }
      });
    }, []);
  const handleGameEnd = function (data) {
    //other code with this variable...
    const { variable } = data;

    //here is the issue; gameId is undefined because it is not set by the state yet because setState is async
    if (gameHistory.filter((game) => game.gameId === gameId).length > 0) {
      return;
    }
    setGameHistory((gameHistory) => {
      const newGameHistory = [...gameHistory];
      newGameHistory.unshift({ gameId: gameId });
      newGameHistory.pop();
      return newGameHistory;
    });
  };

Anyone have an idea?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

react like am i joke to you dude why are you setting gameHistory state twice you can do all your logic then call all setStates at the end like this

    useEffect(() => {
      socket.emit("crash:info", (resp) => {
        const { status, gameId, gameHistory, mockVariable } = resp;

        switch (status) {
          case 2:
            handleGameEnd({ variable: mockVariable, gameId, gameHistory });
            break;
        }


       setStatus(status);
       setGameId(gameId);
       // you already set gameHistory no need for that
       //setGameHistory(gameHistory); 
      });
    }, []);

  const handleGameEnd = function (data) {
    //other code with this variable...
    const { variable, gameId, gameHistory } = data;

    //now you have both gameId and gameHistory 
    if (gameHistory.filter((game) => game.gameId === gameId).length > 0) {
      return;
    }
    setGameHistory((gameHistory) => {
      const newGameHistory = [...gameHistory];
      newGameHistory.unshift({ gameId: gameId });
      newGameHistory.pop();
      return newGameHistory;
    });
    // you can either setState here 
      setGameId(gameId);
      setGameHistory(gameHistory);
    // or back to useEffect block
  };

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