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

281
Vistas
Direct update on state change (React)

So I am currently facing a common issue in which the value of a state in my class component does not change immediately but only after rendering/refreshing the page. I have a state called 'auth' which I want to attribute the value false when clicking 'logout'. When a user presses the button 'logout' I want to immediately put the auth state to 'false' and then redirect them to the login page. But my issue is that this.state.auth remains true if no refresh/rerendering occurs. Keep in mind that it has to work in a Class component like shown below.

import React, { Component, useEffect, useState} from 'react';
import { AuthContext } from '../Context/AuthContext';
    
class Home extends Component {
  state = {
    auth: true
  }

  handleLogOut = () => {
    localStorage.clear();
    sessionStorage.clear();
    this.setState({auth: false});  //Here it stays 'true' up until refresh ?
    this.props.history.push('/'); 
  }

  render() {
    return (
      <AuthContext.Provider value={this.state.auth}>
        <div>
          <button onClick = {this.handleLogOut}>Log out</button>
        </div>
      </AuthContext.Provider>
    );
  }
};
    
export default withRouter(Home);
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

this.setState(
  { auth: false },
  () => this.props.history.push("/")
);
about 4 years ago · Juan Pablo Isaza Denunciar

0

In your specific case, use componentDidUpdate.

You can use it as such

componentDidUpdate(prevProps, prevState) {
  console.log(this.state) // Logs new state.
}

However, I recommend you move toward functional components as componentDidUpdate and similar class-based components are considered legacy.

Resource

about 4 years ago · Juan Pablo Isaza Denunciar

0

I created a little sandbox demo for you here: https://codesandbox.io/s/a-simple-react-router-v4-tutorial-forked-uznym

Your handleLogOut function will read auth as false until React rerenders the component. Barring any errors that may have occurred, you can log the state in the render method and see what it reads there.

  handleLogOut = () => {
    console.log(this.state.auth);
    localStorage.clear();
    sessionStorage.clear();
    this.setState({ auth: false }); //Here it stays 'true' up until refresh ?
    // this.props.history.push("/");
    console.log(this.state.auth);
  };

  render() {
    console.log(this.state.auth);
    ...
  }
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