0
votes

I want to store data via asyncstorage in my react-native app, But I have a problem. I using it like that:

 async componentDidMount() { 
 console.log("Flag1");
 await AsyncStorage.setItem('name', 'I like to save it.');
 console.log("Flag2");
 }

But for some reason I cant reach "Flag2", And I am not getting an error or a data from the await call. I also tried use try/catch, facing the same problem.

edit I noticed that AsyncStorage works for me only when I just open the emulator, after a couple of uses it stops working.

3

3 Answers

2
votes

setItem and getItem are asynchronous, you should send a callback as parameter to get the result. like

componentDidMount(){
    AsyncStorage.setItem('name', 'I like to save it.', ()=>{
        console.log("set item success")
        AsyncStorage.getItem("name", (error, result)=>{
            console.log("get result " + result)
        })
    });
}
1
votes

I think the best practice is, as suggested on react-native docs here, is to wrap it with a try catch expression.

_setAsyncStorage = async () => {
    try { await AsyncStorage.setItem('@name', 'I like to save it');
  } catch (error) {
    // Error saving data
  }
}

you can call this function from any point within your component.

0
votes

Your code should work. I tried

async componentDidMount(){
  await AsyncStorage.setItem('name', 'I like to save it.');
  console.log(await AsyncStorage.getItem('name')); // I like to save it. 
}

Try to check that that data is saved by using await AsyncStorage.getItem.