Reputation: 49
I want to save username in username
state. Now in console I can't see username when I run componentDidMount
.
But if I put a button and I press it I can see username.
componentDidMount(){
this._get_loggin_data();
console.log(this.state.username);
}
_get_loggin_data = async () => {
let result = await SecureStore.getItemAsync('username');
this.setState({username:result})
}
Upvotes: 2
Views: 766
Reputation: 3773
That's because JS is single threaded. As soon as didMount
gets executed, your _get_login_data
function gets queued up in event loop being async in nature and didmount
goes on to execute the console statement after which the _get_login_data
gets actually executed.
You should give a try to write your didMount
as asynchronous too in order to access await for _get_login_data
to get executed before the console.
async componentDidMount(){
await this._get_loggin_data();
console.log(this.state.username);
}
I would recommend you to study Event Loop in JS and how async and callbacks are treated and executed.
Upvotes: 1