A question about AsyncStorage. I'm working on a RN app and I need Async storage to keep track of the login state and token for the user.
The behavior I see with AsyncStorage is really inconsistent. With the below code, I should see a console log of the state of the 'loggedIn' variable. Some runs I do see this, some runs I don't. I'm not sure why? I call this in componentwillmount() for my root component. So I don't think there's any behavior interfering beforehand.
AsyncStorage.getItem('loggedIn').then((loggedIn) => {
console.log('loggedIn:');
console.log(loggedIn);
if ( loggedIn != null)
{
this.state.loggedIn = true;
}
});
This code at one point used to log like it's expected to, printing 'loggedIn: null', but it stopped printing at one point. Even though I didn't change the code. It seems like it doesn't even enter the .then block.
I've also tried using a callback instead of promises and it still doesn't print the result. I don't know what the problem is. Any ideas?
I've downloaded Reactotron to try and track AsyncStorage's behavior. But it doesn't seem to show any change to AsyncStorage when I try setting a variable in another one of my components, as shown in the code block below.
On successful login I try and save the key, but it also doesn't seem to work. I don't get a console log, and I don't see any changes on Reactotron.
AsyncStorage.setItem('key', data.key, () => { AsyncStorage.getItem('key', (err, result) => {
console.log(result)});});
Not sure what other code snippets I need to illustrate the behavior.
This should help
getData = async () => {
try{
await AsyncStorage.getItem('loggedIn', (err, loggedIn) => {
if(!err && loggedIn!=null){
this.setState({loggedIn});
}
})
}catch(e){
console.log("Error ", e);
}
}
Don't forget to call this.getData() wherever you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With