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?
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
};