Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native: setState not updating immediately when logging in console

Tags:

reactjs

The state loggedIn here is updating perfectly because I am changing a button depending on the state. But whenever I am logging in console the value of logged in state immediately after changing it, it shows the opposite. So if the loggedIn just because true it still shows false in console. What is the reason behind it?

constructor(props) {
    super(props);
    this.state = {
        loggedIn: false
    }
}
changeState(val){
    this.setState({
        loggedIn: val
    });
    console.log(this.state.loggedIn);
}
render() {
    return (
        this.state.loggedIn ?  <Home_user onUpdate={(e) => this.changeState(e) } /> : <Auth onUpdate={(e) => this.changeState(e) } />
    )
}
like image 461
Tahnik Mustasin Avatar asked Jun 21 '16 16:06

Tahnik Mustasin


1 Answers

Setting the state is asynchronous so you would almost always see the old value. Instead, use the callback the function provides:

this.setState({
    loggedIn: val
}, () => console.log(this.state.loggedIn));

This is particularly useful when you need to do something AFTER setting a new state.

like image 104
ZekeDroid Avatar answered Oct 09 '22 23:10

ZekeDroid