Home > Mobile >  Best way to update an object's value in array (state) in Vuex
Best way to update an object's value in array (state) in Vuex

Time:10-05

Currently, I made a simple cart in Vue with Vuex. The issue I'm having is that I'm updating the quantity of a product inside a cart object, but this does not update on the front-end view (it's not reactive).

What I've current done is updated an object value inside the cart array, for it to work I needed to set the existing cart to an empty array, then I re-applied the old cart with the new value to the cart state.

What would be the best way to update a value of an object inside an array?

Here are the following relevant data from my module (vuex):

    namespaced: true,
    state: {
        cart: [],
        products: [
            {
                id: 2,
                name: 'Product sweater 2',
            },
            {
                id: 1,
                name: 'Product sweater',
            }
        ]
    },
    mutations: {

        update(state, product) {

            const index = state.cart.findIndex(x => x.id === product.id)

            if (index !== -1) {
                state.cart[index].quantity  
                state.cart = [
                    ...state.cart
                ]
            } else {
                product.quantity = 1
                state.cart.push(product)
            }
        },
   }

CodePudding user response:

You can use Vue.set and Vue.delete to change array and object in vue.js. Vue.set is a tool that allows us to add and change a property to an already reactive object.

Vue.set - API

Reactivity in Depth

CodePudding user response:

It would be better if you send the index of the object such that it will be easy to update the particular value without searching for the item in the array else you can follow the below approach

mutations: {
    update(state, product) {
        // Find index of the item to be updated
        const itemIndex = state.cart.findIndex(x => x.id === product.id)
        state.cart[itemIndex] = product;
    }
}

CodePudding user response:

You can try something like this. Code is self-explanatory

mutations: {
    update(state, product) {
        // Find product index in cart
        const index = state.cart.findIndex(x => x.id === product.id)
        if (index !== -1) {
            // If product is found, update properties
            let productFound = state.resources[index]
            productFound.quantity  
            // Update the product in state
            state.cart = [...state.cart.slice(0, index), { ...productFound, ...product }, ...state.cart.slice(index   1)]
        } else {
            // Add product to state
            product.quantity = 1
            state.cart.push({ ...product })
        }
    }
}
  • Related