Infinitbility
Published in

Infinitbility

React Native Async Storage

React Native Async Storage use for store data in the local storage of React Native App. React Native Async Storage provides lots of methods to store, retrieve, and, remove data from Local storage. generally Async storage use for maintaining the session of the application.

Today We will Learn Simple, Basics, And Advance usages of Async Storage

Async Storage with react native

Installation

For npm users

$ npm add @react-native-community/async-storage

For yarn users

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

Link your library in react native application

$ react-native link @react-native-community/async-storage

Only for iOS applications

$ cd ios/ && pod install

Import package from your component

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

Simple Usages

Store Data on Async

storeData = async () => {
try {
await AsyncStorage.setItem('@storage_Key', 'stored value')
} catch (e) {
// saving error
}
}

Read Data from Async

getData = async () => {
try {
const value = await AsyncStorage.getItem('@storage_Key')
if(value !== null) {
// value previously stored
}
} catch(e) {
// error reading value
}
}

Remove Data from Async

removeValue = async () => {
try {
await AsyncStorage.removeItem('@MyApp_key')
} catch(e) {
// remove error
}

console.log('Done.')
}

Basics Usages

Store JSON on Async

const USER = {
name: 'Tom',
age: 20,
traits: {
hair: 'black',
eyes: 'blue'
}
}
await AsyncStorage.setItem('@MyApp_user', JSON.stringify(USER))

For remove and get same from simple usages

Advanced Usages

Merge JSON on Async

const USER_1 = {
name: 'Tom',
age: 20,
traits: {
hair: 'black',
eyes: 'blue'
}
}

const USER_2 = {
name: 'Sarah',
age: 21,
hobby: 'cars',
traits: {
eyes: 'green',
}
}


mergeUsers = async () => {
try {
//save first user
await AsyncStorage.setItem('@MyApp_user', JSON.stringify(USER_1))

// merge USER_2 into saved USER_1
await AsyncStorage.mergeItem('@MyApp_user', JSON.stringify(USER_2))

// read merged item
const currentUser = await AsyncStorage.getItem('@MyApp_user')

console.log(currentUser)

// console.log result:
// {
// name: 'Sarah',
// age: 21,
// traits: {
// eyes: 'green',
// hair: 'black'
// }
// }
}
}

Get All Keys store on Async

getAllKeys = async () => {
let keys = []
try {
keys = await AsyncStorage.getAllKeys()
} catch(e) {
// read key error
}

console.log(keys)
// example console.log result:
// ['@MyApp_user', '@MyApp_key']
}

Fetch Multiple Data from Async

getMultiple = async () => {

let values
try {
values = await AsyncStorage.multiGet(['@MyApp_user', '@MyApp_key'])
} catch(e) {
// read error
}
console.log(values)

// example console.log output:
// [ ['@MyApp_user', 'myUserValue'], ['@MyApp_key', 'myKeyValue'] ]
}

Set Multiple Data From Async

multiSet = async () => {
const firstPair = ["@MyApp_user", "value_1"]
const secondPair = ["@MyApp_key", "value_2"]
try {
await AsyncStorage.multiSet([firstPair, secondPair])
} catch(e) {
//save error
}

console.log("Done.")
}

Multi Merge Data from Async

const USER_1 = {
name: 'Tom',
age: 30,
traits: {hair: 'brown'},
};

const USER_1_DELTA = {
age: 31,
traits: {eyes: 'blue'},
};

const USER_2 = {
name: 'Sarah',
age: 25,
traits: {hair: 'black'},
};

const USER_2_DELTA = {
age: 26,
traits: {hair: 'green'},
};


const multiSet = [
["@MyApp_USER_1", JSON.stringify(USER_1)],
["@MyApp_USER_2", JSON.stringify(USER_2)]
]

const multiMerge = [
["@MyApp_USER_1", JSON.stringify(USER_1_DELTA)],
["@MyApp_USER_2", JSON.stringify(USER_2_DELTA)]
]


mergeMultiple = async () => {
let currentlyMerged

try {
await AsyncStorage.multiSet(multiSet)
await AsyncStorage.multiMerge(multiMerge)
currentlyMerged = await AsyncStorage.multiGet(['@MyApp_USER_1', '@MyApp_USER_2'])
} catch(e) {
// error
}

console.log(currentlyMerged)
// console.log output:
// [
// [
// 'USER_1',
// {
// name:"Tom",
// age:30,
// traits: {
// hair: 'brown'
// eyes: 'blue'
// }
// }
// ],
// [
// 'USER_2',
// {
// name:'Sarah',
// age:26,
// traits: {
// hair: 'green'
// }
// }
// ]
// ]
}

Multi Remove Data From Async

removeFew = async () => {
const keys = ['@MyApp_USER_1', '@MyApp_USER_2']
try {
await AsyncStorage.multiRemove(keys)
} catch(e) {
// remove error
}

console.log('Done')
}

Clear All Data From Async

clearAll = async () => {
try {
await AsyncStorage.clear()
} catch(e) {
// clear error
}

console.log('Done.')
}

Thanks For Reading…

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store