Identical identification numbers duplicated in Vuex payload multiple times

I'm working on a shopping cart system for an online store, and I want to be able to add products to the cart with unique IDs attached to each one in vuex. Each ID should be specific to that product instance to ensure that no two identical products have the same ID.

When adding a product to the cart, I use the following code:

...mapActions({ addToCart: 'addToCart' })

Within Vuex:

addToCart: (state, payload) => {
    payload['uniqueId'] = uuid();
    state.cart.push(payload);
},

The UUID generation method used is as follows:

const uuid = () => {
    return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
        (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
    )
}

Everything works fine except that all products end up inheriting the ID of the most recently added product.

The state.cart variable stores an array of objects representing the items in the cart.

I also attempted using the npm package uuid, but encountered the same issue.

Answer №1

It appears that the issue may be related to using the same variable reference for payload when committing the mutation, causing changes to affect all instances.

To resolve this, consider breaking the reference in your store implementation:

addToCart: (state, payload) => {
  state.cart.push({
    ...payload, // 👈 using spread syntax breaks the object reference
    uniqueId: uuid()
  })
},

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

Injecting modules dynamically in AngularJS

Is it possible to dynamically perform dependency injections? For example, injecting modules later rather than when creating the root app? I have a website where I want to create one all-encompassing ng-app instead of having separate ng-apps for different ...

The art of designing Mongoose and Router files

Let me share my directory structure with you: bin/ www models/ myMongooseModel.js public/ ... routes/ index.js anotherroute.js views/ ... app.js package.json In my app.js file, I have configured some settings using app.set and app.use comman ...

Using perl ajax to modify a table

In my current Perl script, I am working on a functionality where I retrieve data from an xls file and display it as input text on a webpage. The objective is that when a user selects the edit option from a menu, the entire table fetched from the xls file w ...

Adding a dynamic text field when a checkbox is clicked: A step-by-step guide

To dynamically create a text field when a checkbox in the table is clicked, follow these steps. The table contains around 500 data entries, each with a checkbox for user selection of parameters. For example, if the "Testing 1" checkbox is clicked, the "Tes ...

NodeJS: Use setInterval to continuously execute a loop as long as a specific variable remains true

function setNormal() { console.log(1) } function setAlert() { console.log(2) } function alertFunction() { alertVar = setInterval(alertFunc, 600); } function alertFunc() { setAlert() setTimeout(setNormal, 300) } alertFunction() }); I ...

What is the process of encrypting a password using AngularJS on the client side, transferring it securely to the server through ExpressJS, and then decrypting it on the server

Looking for a simple method to encrypt a password on the client side using angular.js, send it to the server with express.js, and then decrypt it? While there are libraries like angular-bcrypt and similar ones in nodeJS, they may not be suitable as they ma ...

The ZIP file downloaded from NodeJS is corrupted and cannot be opened

Currently, I am utilizing the following code to create a MySQL dump in memory, then zip that SQL file with a password from memory and save it to the hard drive so it can be streamed to the client... /* DUMP - database */ var mysqld ...

Java and JavaScript - Utilizing a Map

I'm currently using Rhino to run JavaScript code within my Java program, but I've encountered a problem with iterating over the map in JavaScript. On the Java side: private final Map<Long, ClassEmployees > employees ; ... employees.put (n ...

Leverage selenium to enter data for numerous elements by utilizing xpath

I am new to using Selenium and I am exploring ways to locate a series of input elements using xpath or css. My goal is to iterate over each element and input text into them. For example: <form> value1 <input type="text" placeholder="value1"> ...

Centering div elements in ASP.NET using C# and Javascript

I am looking to create a functionality on my website where, upon clicking a button, a DIV appears in the center of the browser, overlaying all other content. I have already created the DIV and managed its visibility toggle, but I'm struggling with the ...

Steps for coloring an image using pixel values retrieved from a database

My goal is to create a heat map by dividing an image I captured from Google Maps into a grid, which can be seen here: https://i.sstatic.net/uNv4e.jpg I want to assign colors to specific grid squares based on the number of people living in them. For exampl ...

Looping through items with ng-repeat and creating a submenu with M

When constructing a menu from a JSON file with submenus using the JQuery.mmenu plugin, I encountered an issue when trying to implement the submenu structure with ng-repeat. The raw HTML approach worked perfectly, but as soon as I introduced ng-repeat to dy ...

What is the best way to send a variable to a callback function?

Just starting out with node, express, and javascript. Here's the code from my index.js file in the routers folder. I'm trying to figure out how to pass or access the res variable in the handleImport function. function handleImport(err, stat) { ...

Weird errors popping up when running npm build in ReactJS - lifecycle and export issues arise

Currently facing an issue while trying to build a React project using npm run build for creating a production build Running npm start works perfectly fine and compiles the react code without any issues npm run build - error https://i.sstatic.net/lMfbK.pn ...

Vue-Router: Identified an ongoing redirection loop in a navigation guard while transitioning from the home page to the login page

I need to implement a feature where pages are blocked if there is no authentication token and users are redirected to the login page. I have two .ts pages (main and routes) routes: import { RouteRecordRaw } from 'vue-router'; const routes: Route ...

Improving Performance: Addressing Charset Definition Issue in NextJS Lighthouse Best Practices

Encountering an error on my blog page that states: Properly define charset Error! A character encoding declaration is required. It can be achieved with a tag in the first 1024 bytes of the HTML or in the Content-Type HTTP response header. Find out more a ...

After implementing global navigation guards in Vue-router, an unexpected error message stating "Uncaught TypeError: Cannot read property 'matched' of undefined" is being thrown

After successfully navigating the login process and implementing user-role-based routing, I proceeded to set up authentication guards for different URLs. Though it initially seemed straightforward, I encountered an error that I haven't been able to t ...

Storing JSON values dynamically

On a PHP webpage, I am sending values using JSON. $result = mysql_query("SELECT * FROM user_info"); $i=1; while($row = mysql_fetch_array($result, MYSQL_NUM)) { if(is_array($row) && count($row)>0) { $res[&a ...

Is it possible to generate a basic HTML page using Express JS without utilizing Ejs or any other templating engine

I have a basic HTML file with a Bootstrap form, along with a simple API coded within. In my server.js file, I've specified that when I request /about, it should redirect me to the about.html page. However, instead of redirecting, I'm encountering ...

Troubleshooting problems with populating select options using jQuery on click

After successfully creating a sample in jsfiddle http://jsfiddle.net/9vkk5/ to demonstrate my issue, I have managed to populate the select with data from a database using the following code: $.ajax({ type: "POST", url: "load.php?type=clients", ...