Right way to setItem in AsyncStorage

前端 未结 4 1019
萌比男神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.

提交回复
热议问题