Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right way to setItem in AsyncStorage

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?

like image 551
Boky Avatar asked Apr 29 '17 12:04

Boky


People also ask

How do you setItem an object in AsyncStorage in React Native?

The setItem method saves data to the AsyncStorage and allows a key and a value. Here, the key is a string that the data or value is assigned to: // React Native component const value = { name: "Chimezie", job: "Software Developer" }; const storeUser = async () => { try { await AsyncStorage. setItem("user", JSON.

What is AsyncStorage and how do you use it?

AsyncStorage is an 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.

How do you store data in AsyncStorage?

React Native AsyncStorage saves the data using setItem() method as: AsyncStorage. setItem('key', 'value');


2 Answers

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.

like image 190
atitpatel Avatar answered Nov 10 '22 08:11

atitpatel


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);
    });
  });
});
like image 1
yifan_z Avatar answered Nov 10 '22 09:11

yifan_z