Right way to setItem in AsyncStorage

前端 未结 4 1020
萌比男神i
萌比男神i 2021-02-15 16:57

I want to use AsyncStorage.setItem inside AsyncStorage.getItem. How to do that in right way?

My code is as follows:

createVehic         


        
4条回答
  •  深忆病人
    2021-02-15 17:30

    I don't know if I come too late, but I wrote this for myself :

    import { Base64 } from 'js-base64';
    import { AsyncStorage } from 'react-native';
    
    export async function storeItem(key: string, item: string, isJson: boolean) {
        try {
            return new Promise(async resolve => {
                let stringObject = '';
                if (isJson) {
                    stringObject = JSON.stringify(item);
                } else {
                    stringObject = item.toString();
                }
                let base64Object = await Base64.encode(stringObject);
                await AsyncStorage.setItem(key, base64Object);
                resolve();
            });
        } catch (e) {
            console.log(e);
        }
    }
    
    export async function retrieveItem(key: string, isJson: boolean) {
        try {
            return new Promise(async resolve => {
                let base64Item = await AsyncStorage.getItem(key);
                if (base64Item === null) {
                    resolve(null);
                }
                let item = await Base64.decode(base64Item);
                resolve(isJson ? JSON.parse(item) : item);
            });
        } catch (e) {
            console.log(e);
        }
    }
    
    export async function removeItem(key: string) {
        try {
            return new Promise(async resolve => {
                await AsyncStorage.removeItem(key);
                resolve();
            });
        } catch (e) {}
    }
    

    I use base64 because of the special characters.

    Hope it could helps :)

提交回复
热议问题