Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

93
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda