I am trying to update the data's of asynchStorage
in react native, but the data are not getting updated.
I followed these threads and did the same way, But could not find where it is getting wrong.
Although if i try to add only two objects that works fine but when i try to add product
to productData
, it only returns one old data, the productData
doesn't get updated.
Here is my jsfiddle. http://jsfiddle.net/73ftg295/23/
Can anyone please help me with this. Thank you.
- What is the correct way to use AsyncStorage to update state in React-Native?
- How can I add a key/value pair to a JavaScript object?
Here is my snippet
static addToCart(id,name,qty,price){
//Storing the data into a variable
let product={
id:id,
name:name,
qty:qty,
price:price,
};
//Generate rowid for the product
product.rowId = this.generateHash(product);
//Calling asyncStorage function
AsyncStorage.getItem('CART').then((data) => {
//Check if the data exist or not
if (data !== null){
//Convert the data to an object and store to productData variable
let productData= JSON.parse(data);
//Check if the product with the rowid exist in the store or not
if (this.checkIfExist(product.rowId)){
//If exist increment the quantity of the product
productData[product.rowId].qty += product.qty;
}else{
//If does not exist then add this new product to the existing products
productData[product.rowId] = product; // ERROR HERE !! the new record is not getting added to the productData
}
//Update the storage with new data
AsyncStorage.setItem("CART", JSON.stringify(productData)).done();
cartResponse = productData;
}else{
//If data is null then there is no previous product availabe. Add first product
let cartItem ={};
cartItem[product.rowId] =product;
AsyncStorage.setItem("CART", JSON.stringify(cartItem)).done();
}
//If everything works fine then return true
return true;
}).catch((error)=>{
console.log('Error occurred while adding product to cart',error);
return false;
});
};