React Native: setState is not updated immediately when entering the console

The loggedIn state here is updated beautifully because I change the button depending on the state. But whenever I register a console, the value of the registered state immediately after changing it shows the opposite. Therefore, if loggedIn is only because true, it still shows false in the console. What is the reason for this?

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) } /> ) } 
+5
source share
1 answer

The state setting is asynchronous, so you will almost always see the old value. Instead, use the callback provided by the function:

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

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

+9
source

All Articles