Asyncstorage in react-native with Expo
Published in
2 min readFeb 23, 2022
An asynchronous, unencrypted, persistent, key-value storage API.
Firstly import the package from Expo.
import AsyncStorage from '@react-native-async-storage/async-storage';
Secondly we need to store the data of the project.
Storing string value
const storeData = async (value) => {
try {
await AsyncStorage.setItem('@storage_Key', value)
} catch (e) {
// saving error
}
}
Storing object value
const storeData = async (value) => {
try {
const jsonValue = JSON.stringify(value)
await AsyncStorage.setItem('@storage_Key', jsonValue)
} catch (e) {
// saving error
}
}
thirdly we need to read the data of the project
Reading string value
const getData = async () => {
try {
const value = await AsyncStorage.getItem('@storage_Key')
if(value !== null) {
// value previously stored
}
} catch(e) {
// error reading value
}
}
Reading object value
const getData = async () => {
try {
const jsonValue = await AsyncStorage.getItem('@storage_Key')
return jsonValue != null ? JSON.parse(jsonValue) : null;
} catch(e) {
// error reading value
}
}
Reference methods
1. getItem()
static getItem(key: string, [callback]: ?(error: ?Error, result: ?string) => void)
2. setItem()
static setItem(key: string, value: string, [callback]: ?(error: ?Error) => void)
3. removeItem()
static removeItem(key: string, [callback]: ?(error: ?Error) => void)
4. mergeItem()
static mergeItem(key: string, value: string, [callback]: ?(error: ?Error) => void)
5. getAllKeys()
static getAllKeys([callback]: ?(error: ?Error, keys: ?Array<string>) => void)
6. multiGet()
static multiGet(keys: Array<string>, [callback]: ?(errors: ?Array<Error>, result: ?Array<Array<string>>) => void)
Example code to apply asyncstorage to react native project(CRUD Operation).
// App.jsimport React, { useState, useEffect } from "react";import {Button,StyleSheet,Text,TextInput,View,Keyboard,} from "react-native";import AsyncStorage from "@react-native-async-storage/async-storage";export default function App() {
const [nickname, setNickname] = useState();// Load data when the app startsuseEffect(() => {const firstLoad = async () => {try {const savedNickname = await AsyncStorage.getItem("@nickname");setNickname(savedNickname);} catch (err) {console.log(err);}};firstLoad();}, []);// Create or Update nicknameconst saveNickname = async () => {try {await AsyncStorage.setItem("@nickname", nickname);} catch (err) {console.log(err);}Keyboard.dismiss();};// Delete nicknameconst removeNickname = async () => {try {await AsyncStorage.removeItem("@nickname");setNickname();} catch (err) {console.log(err);}Keyboard.dismiss();};return (<View style={styles.container}>{nickname ? (<Text style={styles.heading}>Hello {nickname}</Text>) : (<Text style={styles.heading}>Create your nickname</Text>)}<TextInputplaceholder="Enter Your Nickname"style={styles.textInput}value={nickname}onChangeText={(value) => {setNickname(value);}}/><View style={styles.buttonContainer}><Button title="Save" onPress={saveNickname} /><Button title="Delete" onPress={removeNickname} /></View></View>);}const styles = StyleSheet.create({container: {flex: 1,flexDirection: "column",backgroundColor: "#fff",alignItems: "center",justifyContent: "center",},heading: {fontSize: 24,},textInput: {width: 300,marginVertical: 30,padding: 10,borderWidth: 1,borderColor: "#000",borderRadius: 50,},buttonContainer: {width: 240,display: "flex",flexDirection: "row",justifyContent: "space-evenly",},});
Follows these CRUD operations carefully and have a good.