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.
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.
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.
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 .
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.
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
}
you could make it asynchronous for example
getData = async () => {
const value = await AsyncStorage.getItem('Yourkey');
this.setState({key: value})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With