How to Save and Retrieve JavaScript Objects through AsyncStorage in React Native
AsyncStorage is used to store data in key-value pairs. Plain and small data can be easily stored with AsyncStorage. If you have something big then adding key-value pairs for every bit of information is ineffective. In such cases, you can convert them to JavaScript objects and store them in AsyncStorage.
Before saving AsyncStorage you need to JSON stringify the object and while retrieving data you need to JSON parse the obtained data.
Make sure that you have installed react native asyncstorage library using any of the following commands. (React Native CLI)
yarn add @react-native-async-storage/async-storage
or
npm install @react-native-async-storage/async-storage
If you are using react native expo then execute the following command.
npx expo install @react-native-async-storage/async-storage
In the example below, I have a JavaScript object named userDetails and I save it to AsyncStorage. I retrieve the data and show it as an alert when the button is clicked. As mentioned earlier I have used JSON.stringify and JSON.parse methods while saving and retrieving data from AsyncStorage in React Native.
import React, {useEffect} from 'react';
import {View, Button, Alert, StyleSheet} from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
const userDetails = {
name: 'Rashid',
gender: 'male',
age: 28,
};
const App = () => {
useEffect(() => {
AsyncStorage.setItem('user', JSON.stringify(userDetails))
.then(() => {
console.log('data saved');
})
.catch(error => {
console.log(error);
});
}, []);
const retrieveData = () => {
AsyncStorage.getItem('user')
.then(value => {
if (value !== null) {
const user = JSON.parse(value);
Alert.alert(`${user.name} ${user.gender} ${user.age}`);
}
})
.catch(error => {
console.log(error);
});
};
return (
<View style={styles.container}>
<Button onPress={retrieveData} title="Show saved Object" />
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#2c3e50',
},
});
export default App;
That’s how you save and retrieve JavaScript objects in react native.