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

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

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