Alex Denor
Alex Denor

Reputation: 137

State array push in vuex is not a function error

I have an array in store/localStorage to save a user's id and work time. However the array.push function is not working.

export const state = () => ({
    Total: []
})

export const mutations = {
    setTotal(state, value){
        state.Total.push(value);
    }
}

I have this in my created:

this.$store.commit("localStorage/setTotal", {id: this.signedInUserID, time: 0});

This is the error I got:

TypeError: state.Total.push is not a function

Upvotes: 0

Views: 1082

Answers (1)

oshell
oshell

Reputation: 9123

Your state is a function, which returns an object. You would be able to access Total by calling state function and then working with the returned object like this: state().Total.push(value).

However in Vuex you create store using Vuex.Store().

const store = new Vuex.Store({
  state: {
    Total: []
  },
  mutations: {
    setTotal(state, value){
      this.state.Total.push(value);
    }
  }
});

If you want to export mutations for testing reasons, you can do so by defining them before and then still assign them in Vuex store.

Upvotes: 1

Related Questions