当前位置:网站首页>Asyncstorage quick start
Asyncstorage quick start
2022-06-22 07:24:00 【Running water I love】
AsyncStorage Quick start
- AsyncStorage Quick start
- characteristic :
- Async Storage Environment building
- API
- `getItem` adopt Key get data
- `setItem` Store the data
- `mergeItem` Merge data items
- `removeItem` Remove an item
- `getAllKeys` Get an item
- `multiGet` Get multiple data items
- `multiSet` Set multiple data items
- `clear` Empty storage items
- `useAsyncStorage` Automatic creation based on Key Addition, deletion and modification of
- Some noteworthy features
- And RN Practice together
AsyncStorage Quick start
This article introduces @react-native-async-storage/async-storage
at present React Chinese net :
Deprecated . Use one of the community packages instead.
Project website :https://react-native-async-storage.github.io/async-storage/
characteristic :
Persistent warehouse
Async Storage One React Native The asynchronous 、 unencrypted 、 persistent Key Value Storage solutions .
Multi platform support
Apply to Android、iOS、Web、MacOS and Windows Data storage solutions for .
concise API
A few tools can simplify your storage processes . Keep it easy 、 Read 、 Merge and delete data !
Async Storage Environment building
NPM:
npm install @react-native-async-storage/async-storage
Yarn:
yarn add @react-native-async-storage/async-storage
Expo CLI:
expo install @react-native-async-storage/async-storage
IOS Please use CocoaPods To add RNAsyncStorage To your project
npx pod-install
High version default link , If you have any link questions, please read https://react-native-async-storage.github.io/async-storage/docs/install
API
getItem adopt Key get data
static getItem(key: string, [callback]: ?(error: ?Error, result: ?string) => void): Promise
Example
getMyObject = async () => {
try {
const jsonValue = await AsyncStorage.getItem('@key')
return jsonValue != null ? JSON.parse(jsonValue) : null
} catch(e) {
// read error
}
console.log('Done.')
}
setItem Store the data
static setItem(key: string, value: string, [callback]: ?(error: ?Error) => void): Promise
Example:
setObjectValue = async (value) => {
try {
const jsonValue = JSON.stringify(value)
await AsyncStorage.setItem('key', jsonValue)
} catch(e) {
// save error
}
console.log('Done.')
}
mergeItem Merge data items
static mergeItem(key: string, value: string, [callback]: ?(error: ?Error) => void): Promise
Example:
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,
// hobby: 'cars',
// traits: {
// eyes: 'green',
// hair: 'black'
// }
// }
}
}
removeItem Remove an item
static removeItem(key: string, [callback]: ?(error: ?Error) => void): Promise
Example
removeValue = async () => {
try {
await AsyncStorage.removeItem('@MyApp_key')
} catch(e) {
// remove error
}
console.log('Done.')
}
getAllKeys Get an item
static getAllKeys([callback]: ?(error: ?Error, keys: ?Array<string>) => void): Promise
Example
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']
}
multiGet Get multiple data items
static multiGet(keys: Array<string>, [callback]: ?(errors: ?Array<Error>, result: ?Array<Array<string>>) => void): Promise
Example:
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'] ]
}
multiSet Set multiple data items
static multiSet(keyValuePairs: Array<Array<string>>, [callback]: ?(errors: ?Array<Error>) => void): Promise
Example:
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.")
}
clear Empty storage items
static clear([callback]: ?(error: ?Error) => void): Promise
Example:
clearAll = async () => {
try {
await AsyncStorage.clear()
} catch(e) {
// clear error
}
console.log('Done.')
}
useAsyncStorage Automatic creation based on Key Addition, deletion and modification of
Source code :
static useAsyncStorage(key: string): {
getItem: (
callback?: ?(error: ?Error, result: string | null) => void,
) => Promise<string | null>,
setItem: (
value: string,
callback?: ?(error: ?Error) => void,
) => Promise<null>,
mergeItem: (
value: string,
callback?: ?(error: ?Error) => void,
) => Promise<null>,
removeItem: (callback?: ?(error: ?Error) => void) => Promise<null>,
}
Return value :
object
Specific Example:
import React, { useState, useEffect } from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
import { useAsyncStorage } from '@react-native-async-storage/async-storage';
export default function App() {
const [value, setValue] = useState('value');
const { getItem, setItem } = useAsyncStorage('@storage_key');
const readItemFromStorage = async () => {
const item = await getItem();
setValue(item);
};
const writeItemToStorage = async newValue => {
await setItem(newValue);
setValue(newValue);
};
useEffect(() => {
readItemFromStorage();
}, []);
return (
<View style={
{ margin: 40 }}>
<Text>Current value: {value}</Text>
<TouchableOpacity
onPress={() =>
writeItemToStorage(
Math.random()
.toString(36)
.substr(2, 5)
)
}
>
<Text>Update value</Text>
</TouchableOpacity>
</View>
);
}
Some noteworthy features
Android Storage capacity limit
Reference documents :https://react-native-async-storage.github.io/async-storage/docs/limits
AsyncStorage for Android Use SQLite As storage backend . Although it has Own size limits ,Android The system also has two known limitations : Total storage size and size limit for each entry .
- By default , The maximum total storage size is 6 MB. You can Use the function flag to specify the new size to Increase this size .
- Each entry is affected by WindowCursor Size limit ,WindowCursor It is one used to get from SQLite Buffer for reading data . At present, its size is about 2 MB. This means that a single item read at a time cannot be greater than 2 MB.AsyncStorage There are no supported workarounds . We recommend keeping your data below that level , Break it up into multiple entries , Instead of a huge entry . This is a
multiGetandmultiSetAPI Where it works .
Next generation storage interfaces
Reference documents :https://react-native-async-storage.github.io/async-storage/docs/advanced/next
Supported platforms :Android
Why migrate
The current implementation of the persistence layer uses SQLiteOpenHelper Created , This is a helper class for managing database creation and migration . Even if this method is powerful , But it lacks compile time query validation and will SQLite Query large templates that map to actual values , This makes this implementation prone to many errors .
This asynchronous storage capability improves the persistence layer , Access... Using modern methods SQLite( Use Room), Minimize possible exceptions . most important of all , It allows access to... From the local side AsyncStorage, This is in Brownfield Integrating It is useful to .
Enable
- In your project
androidDirectory , Find the rootbuild.gradlefile . take Kotlin Dependency added tobuildscript:
buildscript {
ext {
// other extensions
+ kotlinVersion = '1.5.31'
}
dependencies {
// other dependencies
+ classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
}
}
- In the same directory ( Usually
android) Findgradle.propertiesfile ( If it doesn't exist , Then create a ) And add the following lines :
AsyncStorage_useNextStorage=true
And RN Practice together
tool.js
export const propertyVerify = (value, warn = "Parameter does not conform to role.", type="string") => {
if(value == null || value == undefined || value == "" || typeof value != type) {
console.warn(warn);
return false;
}
return true;
}
connect_store.js
import {
propertyVerify} from './tools'
import AsyncStorage,{
useAsyncStorage} from '@react-native-async-storage/async-storage';
const _connect = {
connectedKey : "",
connectedName : "",
}
export const createConnect = (key="", name="") => {
if(propertyVerify(name)) {
_connect.connectedKey = key;
_connect.connectedName = name;
}
return _connect;
}
export const setConnectStorage = async (key, connect) => {
try {
const jsonValue = JSON.stringify(connect);
await AsyncStorage.setItem(key, jsonValue);
} catch(e) {
console.error("Set connect storage error!", e);
}
}
export const getConnectStorage = async (key) => {
try {
const value = await AsyncStorage.getItem(key);
if(value !== null) {
return value;
}
} catch(e) {
console.error("Get connect storage error!", e);
}
}
index.js
import React from 'react';
import {View, StyleSheet, Button, Text} from 'react-native';
import {setConnectStorage, getConnectStorage, createConnect} from '../../../app/store/connect_store';
const Index = () => {
let key = "current_conn";
const setCurrentConnect = (id, name) => {
setConnectStorage(key, createConnect(key=id,name=name));
console.info("Done!")
}
const getCurrentConnect = async () => {
const conn = await getConnectStorage(key);
console.log(conn, "!!!");
}
return (
<View>
<Button
title={"Add Info1"}
onPress={()=>setCurrentConnect("id9988","TP-link 7188")}
/>
<Button
title={"Add Info2"}
onPress={()=>setCurrentConnect("id9990","TP-link 71885G")}
/>
<Button
title={"Get Info"}
onPress={getCurrentConnect}
/>
</View>
);
}
const styles = StyleSheet.create({})
export default Index;
边栏推荐
- Résumé semestriel du programmeur de 33 ans
- Yolov1 (training process)
- okcc呼叫中心的权限管理
- Several methods of array de duplication in JS
- 架构图颜色搭配
- [v4.3] the applet fails to receive the subscription message, and the coupon time on the product details page is displayed incorrectly
- Téléchargement de toutes les versions de chromedriver
- Matlab suddenly fails to open. It disappears after running. There is no solution for the task manager
- Notes on algebra 10.1: understanding of symmetric polynomials and derivation of cubic resolvents
- 咖啡供应链是如何被趟平的?
猜你喜欢

Canoe uses tricks to export data from logging file/trace to Matlab for analysis

New year's Day mall material Icon

Get through version 4.3 mind map
![[standard version 4.3] marketing activities (group bargaining second kill) error reporting under orders](/img/44/2e7789a97fa43d196ef770e8b3c4d4.jpg)
[standard version 4.3] marketing activities (group bargaining second kill) error reporting under orders

Backup the method of uploading babies in Taobao stores to multiple stores

Matlab用深度学习循环神经网络RNN长短期记忆LSTM进行波形时间序列数据预测

What if the finder fails to respond continuously? Finder unresponsive solution tutorial

DETR3D模型源码导读 & MMDetection3D构建流程

Crmeb open source version, a free mall worth trying

RFID仓储管理系统解决方案实施可视化流程
随机推荐
Speed planning generation of coursera self driving car Part4 motion planning
飞桨框架v2.3发布高可复用算子库PHI:重构开发范式,降本增效
What are the ways for Taobao merchants to put their babies on the shelves in batches
Reasons and solutions for Taobao's baby's prompt "sales attribute is required and parameter format is wrong"
What are the functions of Taobao batch copy tool?
[standard version 4.3] marketing activities (group bargaining second kill) error reporting under orders
How to upload Taobao tmall products with one click
【GAN】《ENERGY-BASED GENERATIVE ADVERSARIAL NETWORKS》 ICLR‘17
Batch collection, grab Taobao baby, upload and collect commodity software
Coursera self driving car Part4 motion planning finalproject principle and key code analysis
Yolov1 (training process)
Use of the thrust Library in CUDA
okcc呼叫中心的权限管理
Fundamentals of neural network (notes, for personal use)
Flutter uses the for loop
Several methods of array de duplication in JS
C语言实现的简易考试系统
Get through version - bargain activity
从暴力递归到动态规划
MySQL面试真题(十八)——经营分析实战