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

208
Vistas
function returning opposite boolean value to what I expected

I have this function in my .tsx file:

doIsChecked() {
    var isItChecked = document.getElementById('isPless') as HTMLInputElement;

    console.log('updateDocsFlag before: ' + this.state.updateDocsFlag);
    if (isItChecked.checked) {
        this.setState({ updateDocsFlag: true });
    } else {
        this.setState({ updateDocsFlag: false });
    }
    console.log('updateDocsFlag after: ' + this.state.updateDocsFlag);
}

It get called when a checkbox is ticked/unticked. I noticed that if isItChecked is true updateDocsFlag is false as can be seen in the before and after log entries. This isn't the behaviour I expected Is there something wrong with my code?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

this.setState is asynchronius. it does set the right state,but not at the moment of the call. so when you call

    console.log('updateDocsFlag after: ' + this.state.updateDocsFlag);

you still see the old state. try to do following:

doIsChecked() {
    var isItChecked = document.getElementById('isPless') as HTMLInputElement;

    console.log('updateDocsFlag before: ' + this.state.updateDocsFlag);
    let updateDocsFlag = isItChecked.checked;
    this.setState({ updateDocsFlag });
    console.log('updateDocsFlag after: ' + updateDocsFlag);
}

this way you log not the state, but the value you passing into the state. You suppose to see there the right value. (and the actual state will update with this value after all active functions traces will end)

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