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.