Hello Friends đź‘‹,

Welcome To Infinitbility! ❤️

React Native Asyncstorage - setItem()
React Native Asyncstorage - getItem()
React Native Asyncstorage - removeItem()

React native asyncstorage provide option to store details in application or user phones and use when you want.

In this tutorial, we will learn to store value in asyncstorage with example of diffrent datatypes like string, number, or object.

let start today’s tutorial How to store value in asyncstorage in react native?

Installation

For use asyncstorage in react native we have to first install @react-native-async-storage/async-storage package in our react native project.

  • With npm:
npm install @react-native-async-storage/async-storage
  • With Yarn:
yarn add @react-native-async-storage/async-storage

React Native asyncstorage setItem

Async Storage can only store string data, so in order to store number or object we have to first converts it to string.

For store value in asyncstorage, React native asyncstorage provide setItem() method, it will expect storage key and value.

Check below examples to store string, number, or object in AsyncStorage.

  • Store string example
import AsyncStorage from '@react-native-async-storage/async-storage';

const storeData = async () => {
    await AsyncStorage.setItem('@storage_Key', "value")
}
  • Store number example

To store number in AsyncStorage we have to first convert to string using toString() method.

import AsyncStorage from '@react-native-async-storage/async-storage';

const storeData = async () => {
    let age = 12;
    await AsyncStorage.setItem('@age', age.toString())
}
  • Store object example

To store object in AsyncStorage we have to first convert to string using JSON.stringify() method.

import AsyncStorage from '@react-native-async-storage/async-storage';

const storeData = async () => {
    let user = {
        id: 1,
        name: "infinitbility",
        age: 1.4
    };
    await AsyncStorage.setItem('@user', JSON.stringify(user))
}

Thanks for reading…

if you get stuck, reach me at [email protected]