Search code examples
javascriptvue.jsvuex

Vuex payload unique ID repeated twice (or more)


I'm making a cart system for a shop, and want to add a product to the cart and attach a unique id to it in vuex. Each id is unique to the product instance (i.e. no same product has the same ID, they're completely different)

I add a product like this:

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

In Vuex:

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

uuid() method:

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

All is good apart from that all products inherit the ID from the newest product added.

state.cart is an array of objects.

Also tried this using the npm package uuid, with same results.


Solution

  • I'm going to guess that you're using the same variable reference for payload when committing the mutation so whenever you change one, you change them all.

    The simplest solution is to break the reference. For example, in your store

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