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?
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.
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.
React Native AsyncStorage saves the data using setItem() method as: AsyncStorage. setItem('key', 'value');
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.
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);
});
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With