I have a question about AsyncStorage..
console.log(this.state.UserEmail);
AsyncStorage.setItem('email', JSON.stringify(this.state.UserEmail));
the console log logs the user's email perfectly fine, but for some reason when i try to do
AsyncStorage.getItem("email").then((res) => { this.setState({username: res })});
It seems that the AsyncStorage with the item name of "email" is empty.as it does not return anything if i console.log this.state.username.
Thanks in advance,
Mario
I have a question about AsyncStorage..
console.log(this.state.UserEmail);
AsyncStorage.setItem('email', JSON.stringify(this.state.UserEmail));
the console log logs the user's email perfectly fine, but for some reason when i try to do
AsyncStorage.getItem("email").then((res) => { this.setState({username: res })});
It seems that the AsyncStorage with the item name of "email" is empty.as it does not return anything if i console.log this.state.username.
Thanks in advance,
Mario
Share Improve this question asked Apr 20, 2018 at 13:53 MarioMario 491 silver badge11 bronze badges 6-
Are you calling
getItem
immediately aftersetItem
?setItem
is an async function, so it may not be plete immediately after. – TKoL Commented Apr 20, 2018 at 14:02 - No. I'm calling it further into the application. Could it be because i'm navigating to another view? I wouldnt think so but i'm not sure. – Mario Commented Apr 20, 2018 at 14:04
- AsyncStorage.getItem("email").then(async (res) => { const val = await res; this.setState({username: JSON.parse(val) }) }); – Vraj Solanki Commented Apr 20, 2018 at 16:07
-
AsyncStorage.getItem('email').then(async (res) => { const val = await res; this.setState({username: JSON.parse(val) }) }); console.log(this.props.navigation.state.params.id + " " + this.state.typing + " " + this.state.username);
The params.id works, the this.state.typing works, but the this.state.username does not :/ – Mario Commented Apr 20, 2018 at 16:22 - what is your project version? – Batu Commented Apr 20, 2018 at 17:10
2 Answers
Reset to default 4//check it out !
state = {
UserEmail: '[email protected]'
}
async setValue() {
await AsyncStorage.setItem('email', JSON.stringify(this.state.UserEmail));
}
async getValue() {
try {
const value = await AsyncStorage.getItem('email');
if (value !== null) {
// We have data!!
console.log(value);
}
} catch (error) {
// Error retrieving data
}
}
AsyncStorage.getItem("email").then((res) => { this.setState({username: res })});
to:
AsyncStorage.getItem("email").then(async (res) => {
const val = await res;
this.setState({username: val })
});
should wait for response data before doing setState