Reputation: 223
Im trying to store an object in AsyncStorage then retrieve it and merge it with the current one and save it again, thus keeping and updated object at all time. Im really struggling to understand the way you are supposed to store and manipulate this, any suggestions ? this is done in component will mount when the component and app loads ps I only manage to make a new array element with all the object
retrieve method
_retrieveObj = async () => {
try {
const value = await AsyncStorage.getItem('OBJECT');
if (value !== null) {
return JSON.parse(value);
}
return [];
} catch (error) {
// Error retrieving data
}
};
store method
_storeObj = async (obj) => {
let numberArray = [];
try {
let storedNumbers = await AsyncStorage.getItem('OBJECT');
if (storedNumbers !== null) {
numberArray = JSON.parse(storedNumbers);
}
numberArray.push(obj)
await AsyncStorage.setItem('OBJECT', JSON.stringify(numberArray));
} catch (error) {
console.log(error)
}
};
call within Component
_UpdateAndSave = async (objToDisplay) => {
const storedObj = await this._retrieveObj();
if (storedObj !== objToDisplay) {
const obj = this._merge(storedObj ,objToDisplay);
const objToSave = JSON.stringify(obj);
this._storeObj(objToSave);
}
method to merge objects (found online)
_merge = (a, b) => {
let c = {};
for(let idx in a) {
c[idx] = a[idx];
}
for(let idx in b) {
c[idx] = b[idx];
}
return c;
};
Thanks
Upvotes: 0
Views: 439
Reputation: 842
The reason you are getting an array is because you are saving an array of objectsin your _storeObj function. It looks like you already merge the existing and new objects into one, so you simply have to save the result of the merge. You shouldn't need your _storeObj function.
_UpdateAndSave = async (objToDisplay) => {
const storedObj = await this._retrieveObj();
if (storedObj !== objToDisplay) {
const obj = this._merge(storedObj ,objToDisplay);
const objToSave = JSON.stringify(obj);
await AsyncStorage.setItem('OBJECT', objToSave);
}
Upvotes: 1