React native develops AsyncStorage data storage of seven react navigation

1 Preface

As we all know, there are different ways to persist data in Android and IOS, such as files, databases, shareprefices, etc. AsyncStorage is a simple key value storage system, which is officially recommended by RN. It stores String data, which is a lightweight Data Persistence technology in RN

2 main usage of asyncstorage

export const AsyncStorage: AsyncStorageStatic;
export type AsyncStorage = AsyncStorageStatic;

/**
 * AsyncStorage is a simple, unencrypted, asynchronous, persistent, key-value storage
 * system that is global to the app.  It should be used instead of LocalStorage.
 *
 * It is recommended that you use an abstraction on top of `AsyncStorage`
 * instead of `AsyncStorage` directly for anything more than light usage since
 * it operates globally.
 *
 * On iOS, `AsyncStorage` is backed by native code that stores small values in a
 * serialized dictionary and larger values in separate files. On Android,
 * `AsyncStorage` will use either [RocksDB](http://rocksdb.org/) or SQLite
 * based on what is available.
 *
 * @see https://facebook.github.io/react-native/docs/asyncstorage.html#content
 */
export interface AsyncStorageStatic {
    /**
     * Fetches key and passes the result to callback, along with an Error if there is any.
     */
    getItem(key: string, callback?: (error?: Error, result?: string) => void): Promise<string>;

    /**
     * Sets value for key and calls callback on completion, along with an Error if there is any
     */
    setItem(key: string, value: string, callback?: (error?: Error) => void): Promise<void>;

    removeItem(key: string, callback?: (error?: Error) => void): Promise<void>;

    /**
     * Merges existing value with input value, assuming they are stringified json. Returns a Promise object.
     * Not supported by all native implementation
     */
    mergeItem(key: string, value: string, callback?: (error?: Error) => void): Promise<void>;

    /**
     * Erases all AsyncStorage for all clients, libraries, etc. You probably don't want to call this.
     * Use removeItem or multiRemove to clear only your own keys instead.
     */
    clear(callback?: (error?: Error) => void): Promise<void>;

    /**
     * Gets all keys known to the app, for all callers, libraries, etc
     */
    getAllKeys(callback?: (error?: Error, keys?: string[]) => void): Promise<string[]>;

    /**
     * multiGet invokes callback with an array of key-value pair arrays that matches the input format of multiSet
     */
    multiGet(
        keys: string[],
        callback?: (errors?: Error[], result?: [string, string][]) => void
    ): Promise<[string, string][]>;

    /**
     * multiSet and multiMerge take arrays of key-value array pairs that match the output of multiGet,
     *
     * multiSet([['k1', 'val1'], ['k2', 'val2']], cb);
     */
    multiSet(keyValuePairs: string[][], callback?: (errors?: Error[]) => void): Promise<void>;

    /**
     * Delete all the keys in the keys array.
     */
    multiRemove(keys: string[], callback?: (errors?: Error[]) => void): Promise<void>;

    /**
     * Merges existing values with input values, assuming they are stringified json.
     * Returns a Promise object.
     *
     * Not supported by all native implementations.
     */
    multiMerge(keyValuePairs: string[][], callback?: (errors?: Error[]) => void): Promise<void>;
}

You can see that AsyncStorage stores string string type, which is very similar to shareprefices in Android. If you need to store objects in js, you need to use JSON serialization for storage. Fortunately, the definition of objects in js conforms to the form of JSON objects, so it is very convenient to serialize.

3 AsyncStorage Demo instance

When using AsyncStorage, we need to import this component from react native. Take the common getItem, setItem and removeItem as examples to explain the basic use. Let's take a look at the api introduction

    /**
     * Fetches key and passes the result to callback, along with an Error if there is any.
     */
    getItem(key: string, callback?: (error?: Error, result?: string) => void): Promise<string>;

    /**
     * Sets value for key and calls callback on completion, along with an Error if there is any
     */
    setItem(key: string, value: string, callback?: (error?: Error) => void): Promise<void>;

    removeItem(key: string, callback?: (error?: Error) => void): Promise<void>;

getItem corresponds to getting data. The parameter is to pass in a key and then have a callback. If it is an error, the error is not null. Otherwise, read the result
setItem corresponds to the stored data. It needs to transfer key, data and wrong callback
When the removeItem object deletes data, it needs to pass in the key and the corresponding wrong callback.
Let's see the Demo source code

import React,{Component}from "react";
import {View,TouchableOpacity, Text, TextInput, AsyncStorage} from "react-native";
import Toast, {DURATION} from 'react-native-easy-toast'

const KEY = "key";

export default class AsyncStorageDemo extends Component{


    constructor(props){
        super(props);
    }

    render(){
        return (
            <View>
                {/*Assign to AsyncStorageDemo.text variable*/}
                <TextInput onChangeText={(text) => this.text=text}/>
                <View style={{flexDirection:"row",justifyContent:"space-between", margin:10}}>
                    <TouchableOpacity onPress={() => this.onSave()}>
                        <Text>Preservation</Text>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => this.onRemove()}>
                        <Text>delete</Text>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => this.onFetch()}>
                        <Text>Obtain</Text>
                    </TouchableOpacity>
                </View>
                <Toast ref={(toast) => this.toast = toast}/>
            </View>
        );
    }

    onSave(){
        AsyncStorage.setItem(KEY,this.text,(error) => {
            if (!error){
                this.toast.show("Save successfully",DURATION.LENGTH_SHORT);
            } else {
                this.toast.show("Save failed",DURATION.LENGTH_SHORT);
            }
        })
    }

    onRemove(){
        AsyncStorage.removeItem(KEY,(error) => {
            if (!error){
                this.toast.show("Delete successful",DURATION.LENGTH_SHORT);
            } else {
                this.toast.show("Delete failed",DURATION.LENGTH_SHORT);
            }
        })
    }

    onFetch(){
        AsyncStorage.getItem(KEY,(error,result) => {
            if (!error){
                if (result !== null && result !== ""){
                    this.toast.show("Get success:" + result,DURATION.LENGTH_SHORT);
                } else {
                    this.toast.show("Non-existent" + result,DURATION.LENGTH_SHORT);
                }

            } else {
                this.toast.show("Acquisition failure",DURATION.LENGTH_SHORT);
            }
        })
    }
}

The code is quite simple, so I won't explain it too much. Let's see the operation effect

Tags: React JSON Android iOS

Posted on Thu, 09 Jan 2020 12:57:28 -0500 by generic