I had read a lot of answers of questions about it, but it didn't helped me.
Functional component need once subscribe to events and get data from API to state.
But state don't changes correctly.
const [games, setGames] = useState(null);
const [activeGame, setActiveGame] = useState(null);
const [pending, setPending] = useState(false);
useEffect(() => {
if (games === null) {
setPending(true);
API.Game.get({}).then((res) => {
if (res.success) {
console.log(res.msg.games) // Returning array of games [{...}, {...}]
setGames(res.msg.games);
setActiveGame(res.msg.activeGame);
// Rendered games, but didn't changed state :/
setTimeout(() => console.log(games), 1000) // Returning null (initial state)
}
setPending(false);
});
API.Socket.emit('subscribe', 'game');
API.Socket.on('addGame', (game) => {
setGames((games) => [...games, game]);
});
API.Socket.on('open', (isReconnect) => {
if (isReconnect) API.Socket.emit('subscribe', 'game');
});
}
}, [games, pending, activeGame]);
Depending on answers you provided, I tried this, but it still don't work.
const [games, setGames] = useState([null]);
const [activeGame, setActiveGame] = useState(null);
const [pending, setPending] = useState(false);
const fetchGames = async () => {
setPending(true);
const res = await API.DurakGame.get({});
if (res.success) {
setGames(res.msg.games);
setActiveGame(res.msg.activeGame);
}
setPending(false);
return true;
};
useEffect(() => {
fetchGames();
API.Socket.emit('subscribe', 'durak');
API.Socket.on('addGame', (game) => {
setGames((games) => [...games, game]);
});
API.Socket.on('open', (isReconnect) => {
if (isReconnect) API.Socket.emit('subscribe', 'durak');
});
}, []);