Search code examples
javascriptvue.jsvuex

How to trigger the processing of new values added to a vuex store?


I have a vuex store that stores entries:

const store = createStore({
  state() {
    return {
      entries: [
        {
          id: 1,
          date-of-birth: "2020-10-15T14:48:00.000Z",
          name: "Tom",
        },
      ],
    };
  },
});

I get these entries by using a getter in a computed property:

computed: {
  entries() {
    var entries = this.$store.getters.entries;
  }
}

For some reason, I want to always output the newest date-of-birth in the store. Initially, I was able to do this in two ways:

  • By creating an additional computed property newest_date-of-birth
  • By simply adding a new data variable newest_date-of-birth that gets set within (e.g.) the beforeMounted hook.

However, when I add a new entry (through the app), both these methods do not update newest_date-of-birth as only the computed property entries is triggered.

I tried to solve this in two approaches:

  • When I try to update newest_date-of-birth within the computed property entries, I get advised not to do this as it seems to be bad practise (no-side-effects-in-computed-properties).
  • Also watching over computed property entries does not work; apparently this only works for data variables.

So my question is: How do I update newest_date-of-birth after a value is added to (or removed from, for that matter) the store?

Thanks!


Solution

  • You are only showing the state property of your vuex object. I assume you are also using the mutation property to set internal values.

    If so, all you have to do is set multiple states on a single mutation and both of them will update in your computed values, like this:

    const store = new Vuex.Store({
      state: {
        entries: []
        lastEntrie: null
      },
      mutations: {
        addEntrie (state, entrie) {
          state.entries.push(entrie);
          state.lastEntrie = entrie;
        }
      }
    })
    

    Then, in your computed values:

    computed: {
      myEntries () {
        return this.$store.state.entries
      }
      theLastEntrie () {
        return this.$store.state.lastEntrie
      }
    }