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

96
Visualizações
React State variable keeps resetting and changing within one render

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?

about 4 years ago · Juan Pablo Isaza
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