Sig
Sig

Reputation: 93

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.

Upvotes: 9

Views: 13246

Answers (3)

alipman88
alipman88

Reputation: 33

React Native provides a Settings API that wraps NSUserDefaults, acting as a persistent key–value data store with synchronous reads: https://reactnative.dev/docs/settings

However, that API is only available for iOS – for those looking for cross-platform functionality, here's an NPM package extending support to Android: https://github.com/alipman88/react-native-cross-platform-settings?tab=readme-ov-file

Upvotes: 0

linux
linux

Reputation: 151

you could make it asynchronous for example

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

  }

Upvotes: 1

nima moradi
nima moradi

Reputation: 2618

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
}

Upvotes: 6

Related Questions