export default function Questionnaire(props) {
const initialState = {
questionCount: 0,
is_host: false
}
const [ roomData, setRoomData ] = useState(initialState)
const { roomCode } = useParams()
const [ displayedTable, setDisplayedTable ] = useState(1);
useEffect(() => {
fetch("/audio/get-room" + "?code=" + roomCode)
.then(res => res.json())
.then(data => {
setRoomData({
roomData,
questionCount: data.questionCount,
is_host: data.is_host,
})
})
window.addEventListener('keydown', (e) => {
console.log("questionCount 1:", roomData.questionCount);
if (e.keyCode == '39') {
setDisplayedTable(showNextStage(displayedTable, roomData.questionCount));
} else if (e.keyCode == '37') {
setDisplayedTable(showPreviousStage(displayedTable));
}
});
// cleanup this component
return () => {
window.removeEventListener('keydown', (e) => {
if (e.keyCode == '39') {
setDisplayedTable(showNextStage(displayedTable, roomData.questionCount));
} else if (e.keyCode == '37') {
setDisplayedTable(showPreviousStage(displayedTable));
}
});
};
},[roomCode,setRoomData])
console.log("questionCount 2:", roomData.questionCount);
return (
<div>
{components[displayedTable]}
</div>
)
}
Every time the State refreshes, the two console.logs() return "questionCount 1: 0" and "questionCount 2: 5" (the value fetch() retrieves). But since questionCount is only set to 0 in the initial UseState(), it shouldn't be resetting to 0 and should remain at 5 after it gets set to that. But it doesn't. Why is this? How is it even possible for the one State variable to have two different values in the one render(), when State changes are meant to rerender the page?