Search code examples
vue.jsvuex

update component when updating a resource


I created a simple todo app and when deleting an item from my vuex store the component rendering the todo list updates automatically. When updating a todo item from "pending" to "completed" the component doesn't update automatically. The store gets updated but I think there is no trigger that says

hey, a resource from an array got updated, please render again

How can I force it to do so?

I created a small example showing what I mean, if you delete a todo item the component will update. If you click on a "update" button it will not change.

https://codesandbox.io/s/x3wv1yp33w


Solution

  • It's a reactivity problem:

    Vue does not allow dynamically adding new root-level reactive properties to an already created instance. However, it’s possible to add reactive properties to a nested object using the Vue.set(object, key, value) method (source)

    In your store's UPDATE_TODO mutation, change this line:

    state.todos[todoIndex] = updatedTodo
    

    to this:

    Vue.set(state.todos, todoIndex, updatedTodo)
    

    and of course, add import Vue from 'vue' at the top of the file.
    It should work this way.