0
votes

I store data in state as array and I want to change the value of the object. How can I change the id 1 value to true with vuex actions?

state.js

const array=[]

mutations.js

storeArray(state, data) {
    state.array = data;
  }

actions.js

async changeValue({ state, dispatch, commit }, id) {
    const item = await state.array[id].value;

    await commit('storeArray', { value: true });

  },

array looks like

[{
    id: "1",
    value: 'false'
}, {
    id: "2",
    value: 'true'
}]

1
What you're actually doing is just replacing the whole data of array. You rather want to loop through all elements, check which one is the desired element/index and adjust that data accordingly. - Aer0
you not need use actions for this. - Christian Carrillo

1 Answers

0
votes

You need to know beforehand the id and also the value of the new array. To find and change the desired object in the state array, you can use the mutation in the example below:

const store = new Vuex.Store({
  state: {
    objects: [{ id: 1, value: true }, { id: 2, value: true }]    
  },
  mutations: {
    changeObjectValue (state, { id, value }) {
        const found = state.objects.find(item => item.id === id);
        found.value = value;               
    },
  },
});

This way you can commit inside one action like this:

store.commit('changeObjectValue', {id: 2, value: false});

Check this example on plnkr