React-native sync storage solution

Sig picture Sig · Mar 3, 2018 · Viewed 8.6k times · Source

In native iOS code, I could use the NSUserDefaults to store and fetch data, which are sync operations. In react-native the offer is to use AsyncStorage, but I need a solution for sync storing, like NSUserDefaults. I'm gonna use the result of data fetching to determine which screen to show, but since it's async I always get undefined when trying to fetch the persisted data.

Answer

nima moradi picture nima moradi · Mar 3, 2018

after calling

AsyncStorage.getItem('@MySuperStore:key');

react-native will call native function dependent on your platform in other thread then it will return a promise to resolve it ,so if call like this

  let value =  AsyncStorage.getItem('@MySuperStore:key');
   value ++;

your value is not valid cause it data will be available later
the correct way to do is :

try {
  const value = await AsyncStorage.getItem('@MySuperStore:key');
  if (value !== null){
    // We have data!!
    console.log(value);
  }
} catch (error) {
  // Error retrieving data
}

other way of doing this is

  try {
      AsyncStorage.getItem('@MySuperStore:key',(value )=>{  
      if (value !== null){
        // We have data!!
    console.log(value);
  }});

} catch (error) {
  // Error retrieving data
}