Tengo cierta confusión acerca de implementar algo usando componentes funcionales de React. Sé que useState es asíncrono y no refleja el valor cuando lee después del estado de mutación. Sin embargo, no tengo idea de cómo implementar lo que estoy tratando de hacer. Básicamente, en mi componente React, cuando se monta, le pido al servidor información de back-end a través de una conexión websocket y lo configuro en estado. Inmediatamente después de hacer esto, ejecuto un método basado en un interruptor; sin embargo, todavía no puedo acceder al estado en el método porque acabo de mutar el estado y debido a que es asíncrono, los cambios no se reflejan directamente. Aquí está mi código:
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; }); };
¿Alguien tiene una idea?
reacciona como si fuera una broma, amigo, ¿por qué estás configurando el estado del historial del juego dos veces? Puedes hacer toda tu lógica y luego llamar a todos los estados al final de esta manera.
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 };