Right way to setItem in AsyncStorage

Boky picture Boky · Apr 29, 2017 · Viewed 17.8k times · Source

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

My code is as follows:

createVehicle: function (vehicle, cb) {
    AsyncStorage.getItem('vehicle')
    .then(json => {

        let vehicles = [];

        if (json) {
            vehicles = JSON.parse(json);
            let o_vehicle = filter(vehicles, {autralis_id: vehicle.autralis_id});
            if (o_vehicle.length > 0) {
                cb(o_vehicle[0].id);
                return;
            } else {
                vehicles.push(vehicle);
            }
        } else {
            vehicles.push(vehicle);
        }
        AsyncStorage.setItem('vehicle', JSON.stringify(vehicles), () => {
            cb(vehicle.id + 1)
        });
    }).done();
},

Is that the right way to do it?

Answer

atitpatel picture atitpatel · Apr 29, 2017

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.