Right way to setItem in AsyncStorage

前端 未结 4 1018
萌比男神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:14

    I have created a service for Storage which can be used in the entire project as and when required by passing the required params. Have a look :

    export default {
    async setItem(key, value) {
        try {
            return await AsyncStorage.setItem(key, JSON.stringify(value));
        } catch (error) {
            // console.error('AsyncStorage#setItem error: ' + error.message);
        }
    },
    async getItem(key) {
        return await AsyncStorage.getItem(key)
            .then((result) => {
                if (result) {
                    try {
                        result = JSON.parse(result);
                    } catch (e) {
                        // console.error('AsyncStorage#getItem error deserializing JSON for key: ' + key, e.message);
                    }
                }
                return result;
            });
    },
    async removeItem(key) {
        return await AsyncStorage.removeItem(key);
    }
    }
    

    This is by far the best practice I have come across till the date. You should use it too.

    0 讨论(0)
  • 2021-02-15 17:17
    import React, { Component } from 'react'
    import { StatusBar } from 'react-native'
    import { AsyncStorage, Text, View, TextInput, StyleSheet } from 'react-native'
    class AsyncStorageExample extends Component {
       state = {
          'name': ''
       }
       componentDidMount = () => AsyncStorage.getItem('name').then((value) => this.setState({ 
    'name': value }))
       setName = (value) => {
          AsyncStorage.setItem('name', value);
          this.setState({ 'name': value });
       }
       render() {
          return (
         <View style = {styles.container}>
            <TextInput style = {styles.textInput} autoCapitalize = 'none'
            onChangeText = {this.setName}/>
            <Text>
               {this.state.name}
            </Text>
         </View>
          )
       }
    }
    export default AsyncStorageExample
    const styles = StyleSheet.create ({
       container: {
          flex: 1,
          alignItems: 'center',
          marginTop: 50
       },
       textInput: {
          margin: 5,
          height: 100,
          borderWidth: 1,
          backgroundColor: '#7685ed'
       }
    })
    
    0 讨论(0)
  • 2021-02-15 17:22

    Please refer to this official document, it uses getItem inside setItem, So I think you could also use setItem inside getItem, because the return value is just a Promise for both getItem and setItem.

    AsyncStorage.setItem('UID123', JSON.stringify(UID123_object), () => {
      AsyncStorage.mergeItem('UID123', JSON.stringify(UID123_delta), () => {
        AsyncStorage.getItem('UID123', (err, result) => {
          console.log(result);
        });
      });
    });
    
    0 讨论(0)
  • 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 :)

    0 讨论(0)
提交回复
热议问题