This is my code
import { defineStore } from "pinia"; export const DB_CART = defineStore("CART", { state: () => ({ CART: [ { $id: "62616ffc6d13e2a9eb04", quantity: 1 }, { $id: "6261711719aa15827836", quantity: 1 }, { $id: "6275c020740fbd04db50", quantity: 1 } ], }), actions: { // INCREMENT PRODUCT QUANTITY IN CART incrementCartQuantity(id) { const cartItem = this.CART.find(item => item.$id = id); cartItem.quantity++; }, // DECREMENT PRODUCT QUANTITY IN CART decrementCartQuantity(id) { const cartItem = this.CART.find(item => item.$id = id); if (cartItem.quantity === 1) return cartItem.quantity--; }, // ADD PRODUCT TO CART addToCart(item) { this.CART.push(item) } }, persist: true })
I want to understand why the array rearranges when I increment or decrement the cart item starting from the second one in the array.
incrementCartQuantity(id) { const cartItem = this.CART.find(item => item.$id = id); cartItem.quantity++; console.log(this.CART) /*EXPECTED OUTPUT [ { $id: "62616ffc6d13e2a9eb04", quantity: 1 }, { $id: "6261711719aa15827836", quantity: 1 }, { $id: "6275c020740fbd04db50", quantity: 1 } ] *//*RETURED OUTPUT [ { $id: "6261711719aa15827836", quantity: 2 }, { $id: "6261711719aa15827836", quantity: 1 }, INCREMENTED OBJECT { $id: "6275c020740fbd04db50", quantity: 1 } ] */ },
In my Vue component, on incrementCartItem, I find that the entire array gets shuffled and pops the top array and replaces it with the item that is being mutated I don't think arrays are affected in any way.
P粉1558329412024-03-28 15:26:21
Your find
method is performing an assignment "=" instead of a comparison "= == ".
replace
this.CART.find(item => item.$id = id);
and
this.CART.find(item => item.$id === id);
In both shopping cart methods.
Your find
will assign the searched id
to the $id
of the first item each time it is run.