Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating object in array with Vuex [duplicate]

How can I update an object inside an array with Vuex? I tried this, but it didn't work:

const state = {
  categories: []
};

// mutations:
[mutationType.UPDATE_CATEGORY] (state, id, category) {
  const record = state.categories.find(element => element.id === id);
  state.categories[record] = category;
}

// actions:
updateCategory({commit}, id, category) {
  categoriesApi.updateCategory(id, category).then((response) => {
    commit(mutationType.UPDATE_CATEGORY, id, response);
    router.push({name: 'categories'});
  })
}
like image 493
Thuan Nguyen Avatar asked May 19 '18 06:05

Thuan Nguyen


1 Answers

[mutationType.UPDATE_CATEGORY] (state, id, category) {
  state.categories = [
     ...state.categories.filter(element => element.id !== id),
     category
  ]
}

This works by replacing the 'categories' array with the original array without the matching element, and then concatenating the updated element to the end of the array.

One caveat to this method is that it destroys the order of the array, although in a lot of cases that won't be a problem. Just something to keep in mind.

like image 86
ArtemSky Avatar answered Oct 19 '22 05:10

ArtemSky