Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-native sync storage solution

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.

like image 627
Sig Avatar asked Mar 03 '18 15:03

Sig


People also ask

What is Sync storage React Native?

we are going to use sync-storage library. this library is great that uses async storage to save data asynchronously and uses memory to load and save data instantly synchronously, so we save data async to memory and use in app sync, so this is great.

Is React Native async storage deprecated?

Deprecated. Use one of the community packages instead. AsyncStorage is an unencrypted, asynchronous, persistent, key-value storage system that is global to the app. It should be used instead of LocalStorage.

How do I permanently store data in React Native?

In React Native applications, data can be persisted locally using AsyncStorage . AsyncStorage is an asynchronous, persistent, key-value storage system that is global to the entire app. Redux Persist is a tool used to seamlessly save the application's Redux state object to AsyncStorage .

Is React Native async storage safe?

However, it is not advisable to store sensitive information in AsyncStorage since it is not safe for sensitive information. This is because anyone with access to your phone can read the data stored in your phone's document file system.


2 Answers

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
}
like image 180
nima moradi Avatar answered Oct 20 '22 03:10

nima moradi


you could make it asynchronous for example

   getData = async () => {
       const value = await AsyncStorage.getItem('Yourkey');
        this.setState({key: value})

  }
like image 1
linux Avatar answered Oct 20 '22 04:10

linux