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);
CodePudding user response:
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.
CodePudding user response:
this.setState(
{ auth: false },
() => this.props.history.push("/")
);
CodePudding user response:
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);
...
}