im using async storage in my app to keep product name, color, size and number of piece. i can't do that if it's same name, color and size i want to increase piece only. i couldn't think of it.. would you guys help me out
try {
const jsonValue = await AsyncStorage.getItem('shoppingCart');
let cartitem = [
{
ProductDescription: product[0].ProductDescription,
ItemCode: product[0].ProductCode,
ColorCode: colorPicked,
ItemDim1Code: sizePicked,
Qty1: piece,
Price: price,
keyForList: keyForList,
},
];
if (jsonValue !== null) {
let newCart = JSON.parse(jsonValue).concat(cartitem);
AsyncStorage.setItem('shoppingCart', JSON.stringify(newCart));
} else {
AsyncStorage.setItem('shoppingCart', JSON.stringify(cartitem));
}
}
Try it this way:
try {
let existingCart = await AsyncStorage.getItem('shoppingCart');
let cartItem = [
{
ProductDescription: product[0].ProductDescription,
ItemCode: product[0].ProductCode,
ColorCode: colorPicked,
ItemDim1Code: sizePicked,
Qty1: piece,
Price: price,
keyForList: keyForList,
},
];
if existingCart !== null {
// We have a cart already, now we have to check if any item in cart is the same as our cartItem; existingCart should be kept as an array
existingCart.forEach((product, index) => {
if (product.ItemCode == cartItem.ItemCode &&
product.ItemCode == cartItem.ColorCode) {
// you can modify this condition by your needs
existingCart[index].Qty1 += 1
}
else {
// the item doesn't match any items, therefore we add it to the cart
existingCart.push(cartItem)
}
})
} else {
// the cart is empty, therefore we put the first item in it
existingCart = [cartItem]
}
// and we update the local storage with the cart
AsyncStorage.setItem('shoppingCart', JSON.stringify(cartitem));
}