当前位置:网站首页>Asyncstorage quick start

Asyncstorage quick start

2022-06-22 07:24:00 Running water I love

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 multiGet and multiSetAPI 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

  1. In your project android Directory , Find the root build.gradle file . take Kotlin Dependency added to buildscript
buildscript {
    ext {
        // other extensions
+        kotlinVersion = '1.5.31'
    }
    
    dependencies {
        // other dependencies
+        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
    }
}
  1. In the same directory ( Usually android) Find gradle.properties file ( 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;
原网站

版权声明
本文为[Running water I love]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202220536274573.html