My code is here:
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 am curious why when I increment or decrement a cart item starting from the second in the array, the array reorders.
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, when I incrementCartItem, I notice that the entire array seems to shuffle and replace the top item with the mutated one. This behavior puzzles me as I expect the array not to be affected at all.