How to Save and Retrieve JavaScript Objects through AsyncStorage in React Native

Last Updated on December 13, 2020.

AsyncStorage is used to store data in key value pair. Plain and small data can be easily stored with AsyncStorage. If you have something big then adding key value pair for every bit information is ineffective. In such cases, you can convert them to JavaScript object and store into 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.

yarn add @react-native-async-storage/async-storage

or

npm install @react-native-async-storage/async-storage

In the example below, I have a JavaScript object named userDetails and I save it to AsyncStorage in componentDidMount life cycle. I retrieve the data and show it as 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.

Class based component

//import liraries
import React, {Component} from 'react';
import {View, Button, Alert, StyleSheet} from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';

// create a component
class MyClass extends Component {
  componentDidMount() {
    const userDetails = {
      name: 'Rashid',
      gender: 'male',
      age: 28,
    };

    AsyncStorage.setItem('user', JSON.stringify(userDetails))
      .then(() => {
        console.log('data saved');
      })
      .catch((error) => {
        console.log(error);
      });
  }

  retrieveData = () => {
    AsyncStorage.getItem('user')
      .then((value) => {
        const user = JSON.parse(value);
        Alert.alert(`${user.name} ${user.gender} ${user.age}`);
      })
      .catch((error) => {
        console.log(error);
      });
  };

  render() {
    return (
      <View style={styles.container}>
        <Button onPress={this.retrieveData} title="Show saved Object" />
      </View>
    );
  }
}

// define your styles
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#2c3e50',
  },
});

//make this component available to the app
export default MyClass;

Function based component

import React, {useEffect} from 'react';
import {View, Button, Alert, StyleSheet} from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';

const App = () => {
  const userDetails = {
    name: 'Rashid',
    gender: 'male',
    age: 28,
  };

  useEffect(() => {
    AsyncStorage.setItem('user', JSON.stringify(userDetails))
      .then(() => {
        console.log('data saved');
      })
      .catch((error) => {
        console.log(error);
      });
  }, [userDetails]);

  const retrieveData = () => {
    AsyncStorage.getItem('user')
      .then((value) => {
        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.

Leave a Reply

%d bloggers like this: