VueX Patterns: Updating in Array

When working on a type of entity, it’s common to post the new or updated entity to the server and then need to update it in the local vuex data store.

This is a simple pattern that propagates the changes to the UI displaying the list of entities.

1. Save the entity, from the UI.

 this.$store
          .dispatch('catalogs/create', {
            catalog: this.user
          })

2. POST the entity to the server in a vuex action, and pass the response to a mutation.
Note we also return the response data, in case the UI needs it for a flash message.

 async create (context, { user }) {
    const responseUser = await this.$axios.$post('users', user)
    context.commit('userFetched', responseUser.data)
    return responseUser
  },

3. Replace the object in array if it already exists. If it doesn’t exist, push it to the bottom of the array. Clone the array to trigger a UI update.

  userFetched (state, user) {
    const existsAtIndex = state.users.data.findIndex(u => u.id === user.id)

    if (existsAtIndex !== -1) {
      state.users.data[existsAtIndex] = user
    } else {
      state.users.data.push(user)
    }

    state.users.data = [...state.users.data]
  }

4. The UI which lists these users (UserRow below) will update itself with the new entry.

 computed: mapState({ users: state => state.users.users }),
<UserRow v-for="user in users.data" :key="user.id" :user="user" />