Nuxt 3: Pinia: How does mutating my state affect the integrity of the entire array?

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.

Answer №1

Your locate function appears to be utilizing an assignment operator "=" instead of a comparison operator "===".

Please update the following:

  this.CART.locate(item => item.$id = id);

To:

  this.CART.locate(item => item.$id === id);

Ensure to make this change in all instances where the cart methods are used.

The current implementation of your locate function results in assigning the searched id to the first item's $id property during each iteration.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to loop through an object while keeping track of its value types

I have a JSON file containing UI adjustments sourced from the API: interface UIAdjustmentsJSON { logoSize: number; themeColor: string; isFullScreen: boolean; } To simplify things, let's utilize a static object: const adjustments: UIAdjust ...

Executing a batch job array in SLURM where multiple instances of the same script are run simultaneously with distinct input string arguments

Looking for guidance on running a script with different input arguments as strings? Check out this thread for a similar question focusing on numerical arguments. If you have a script (myscript.R) that requires two string arguments: "text-a" and "text-A", ...

Implementing the Applet Param Tag using JavaScript or jQuery

<applet id="applet" code="myclass.class"> <param name="Access_ID" value="newaccessid"> <param name="App_ID" value="newappid"> <param name="Current_Url" value="newticketurl"> <param name="Bug_ID" value="newbugid"&g ...

Retrieving the necessary key values from a JSON dictionary

I'm attempting to retrieve keys from a dictionary using JavaScript. The user uploads a .json file containing the dictionary, and I want to display the keys from that uploaded dictionary. It's important to note that only .json dictionaries can be ...

Why is the response undefined when I resize an image twice using a JavaScript promise chain?

When I attempt to resize an image using the sharp library twice in my route handler, the result returned is undefined. Despite the resized images being displayed, it seems that calling image.resize and .toBuffer() multiple times is causing corruption in th ...

Utilize vue.js input field to search for a specific username within a constantly updating list of users

I have created an input search functionality to filter a list of users using PHP. Now, I am attempting to implement the same filtering feature in Vue.js so that when a user searches for a name, the filtered user will be displayed in the list. Below is the ...

Vue JS: Issue with computed property not triggering v-if condition

Why aren't v-ifs being invoked when a method sets a computed property? I always believed that a computed property functioned similarly to a 'regular' property. // In this example, theState cannot be moved into the Vue object var theState ...

Error: The function pathRegexp is not defined

While attempting to conduct tests on my project with jest, I encountered an error code that seems unrelated to the actual testing process. It appears to be more of a dependency or Node Express compatibility issue. `● Test suite failed to run TypeError: ...

Switching between click and mouseenter in Angular 2+ is made easy with

I am currently working on developing a component for my application's menu. One of the requirements is that the sub-menus should open on mouseenter when the menu is in compact mode, and on click when it is in wide mode (both of these are defined as cs ...

Dynamic VueJS v-model binding target

We are currently in the process of designing a form with numerous dependencies that span across different levels of inputs. For example, if parent1.input1 = 'test', then child1.input1 should also be 'test'. However, if child1.input2 = & ...

Error encountered: The call stack size has been exceeded due to the combination of Node JS, MongoDB, and Mongoose

I am facing a RangeError issue while attempting to create a new object using a predefined schema and inserting it into my mongodb database. I need assistance in debugging this error and finding a solution for it. Any help would be appreciated, thanks. App ...

Combine all possible pairings of elements from two distinct arrays

Is there a way to combine the elements of two arrays and return them in a new array? Let's say we have these two arrays: const whoArr = ["my", "your"]; const credentialArr = ["name", "age", "gender" ...

Attempting to transfer an image as a byte array from the Spring backend to the Angular frontend, however:

The backend code: @GetMapping("datamatrix") public ResponseEntity<byte[]> generarDataMatrix(Long id) throws IOException { byte[] dataMatrixEnBytes = dataMatrix.generarDataMatrixImagen(id.toString(), id); HttpHeaders headers = new ...

sole active component present

In my redux store, I have an array called rooms that is fetched from the server. In my component, I fetch this array from the store, map it, and display elements with the value of room['foo']. However, I am facing a problem where when a user clic ...

Generate a string by splitting an Array with new lines in Swift

While working on my iOS app, I encountered an issue. I need to create a single string from an array of strings containing the address of a specific location. This array is generated through reverse geocoding using CLGeocoder. Here is the code snippet that ...

Discover arrays that have a common element within a group of arrays. There may be zero or multiple instances of matches

After analyzing the data structure below: array (size=3) 0 => array (size=4) 0 => string 'apple' (length=5) 1 => string 'colophon' (length=8) 2 => string 'byo-fusion-drive' (length=16) ...

Obtain specific element from a list using attribute in JavaScript

Imagine having a collection like this: navigation: [ { title: "Overview", icon: "mdi-view-dashboard", active: false, id: 0, }, { title: "Personal Information ...

The dynamic array is limited to allocating just a single element

After extensive searching, I have come up empty-handed on this issue. The code snippet in question is as follows: #include<iostream> using namespace std; int main() { int *newArray; int size; cout << "enter size: "; cin >> size; new ...

Is there a way to display the JavaScript widget exclusively on the homepage or main page

How can I limit the display of a Twitter widget on my blog page to only show on the main page and hide it when visitors navigate to sub-pages or individual blog entries? ...

What sets apart `this.user.id` from `this.user = {id: ....}`?

I am puzzled by the error thrown in the code below: import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-user', templateUrl: './user.compone ...