0
votes

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

2
Are you calling getItem immediately after setItem? setItem is an async function, so it may not be complete immediately after. - TKoL
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
AsyncStorage.getItem("email").then(async (res) => { const val = await res; this.setState({username: JSON.parse(val) }) }); - Vraj Solanki
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
what is your project version? - Batu

2 Answers

4
votes

//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
    }
 }
0
votes
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