Update a single item in a list with vuex

07 Feb 2022 in TIL

I recently needed to find an item in a list of objects by ID and update one of it’s properties whilst working with Vue 3 and VueX. It took me longer than I'd like to admit to figure out, so I'm writing it down here.

Due to how objects are passed by reference in JS, you can reference the item using Object.assign to update a single property.

Here’s the store, including a mutation to update the value:

js
import { createStore } from "vuex";
const store = createStore({
state() {
return {
items: [
{ id: 1, value: "One", color: "red" },
{ id: 2, value: "Two", color: "yellow" },
{ id: 3, value: "Three", color: "skyblue" },
],
};
},
mutations: {
setColor(state, { id, color }) {
console.log(`Setting block ${id} to ${color}`);
const item = state.items.find((i) => i.id == id);
if (item) {
Object.assign(item, { ...item, color });
}
},
},
});
export default store;

Here’s how I called the mutation from the component:

js
setColor(color) {
store.commit("setColor", { id: this.id, color });
return false;
}

The GitHub repo in this post renders a sample application where you can change the colour of some blocks.