I'm working in React and want to iterate the 'amount' property an Object in my 'cart' array based on if it matches the item that had the 'iterate' button pressed.
My original solution was this...
setCart((cart) => {
const itemMatch = cart.find((cartItem) => cartItem.name === item.name);
if (itemMatch !== undefined) {
itemMatch.amount = itemMatch.amount 1;
} else {
cart.push(item);
}
return [...cart];
})
However, the iteration was counting by two's.
My second solution was this...
setCart((cart) => {
const updatedCart = cart.map((cartItem) => {
if (cartItem.name === item.name) {
return {...cartItem, amount: cartItem.amount item.amount}
} else {
return cartItem
}
})
return updatedCart;
})
This solution works but I can't figure out what the difference between these two is. If anyone could help explain the difference that would really help me understand. Thanks.
CodePudding user response:
In first solution you push items in already existing array which already have all those items.
offtop: Second solution is also better in terms of not mutating existing data.
CodePudding user response:
In here you're doing different stuff.
Lets suppose you have a sample input like this:
const item = { name: "abc", amount: 5 }
const cart = [
{ name: "ab", amount: 15 },
{ name: "def", amount: 10 }
]
In Scenario 1:
const setCart = ((cart) => {
/* first finding if the object which are already exist in cart array
is also exist in item object or not. */
const itemMatch = cart.find((cartItem) => cartItem.name === item.name);
// if item found increase amount by 1
if (itemMatch !== undefined) {
itemMatch.amount = itemMatch.amount 1;
} else { // if item not found add that item to array
cart.push(item);
}
// and returning it
return [...cart];
})
// output
/* [
{ name: 'ab', amount: 15 },
{ name: 'def', amount: 10 },
{ name: 'abc', amount: 5 }
] */
In Scenario 2:
const setCart = ((cart) => {
// looping into the cart array and searching if item exist in cart or not
const updatedCart = cart.map((cartItem) => {
// if item which are in cart is also exist
if (cartItem.name === item.name) {
// return all oder cart item, and update the amount
return {...cartItem, amount: cartItem.amount item.amount }
} else {
// return the cart item as it is
return cartItem
}
})
// returning the cart array
return updatedCart;
})
// output
/* [
{ name: 'ab', amount: 15 },
{ name: 'def', amount: 10 }
] */
In Scenario 2,
you can never be able to add a new item into cart, because you're looping into cart item and checking if item exist or not (if exist update the cart, and if not exist just return the cart item as it is).
In Scenario 1,
you're first finding if the cart item is exist or not, and ensure if the item is already exist in cart just update the amount, and if not exist then add item to cart. (This works in real Scenario)