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

276
Visualizações
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 Respostas
Responde à pergunta

0

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

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 Relatório

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 Relatório
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