0

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

4
  • The "localStorage/" prefix implies you have a namespaced Vuex module. Did you set that up properly? Commented Feb 7, 2020 at 8:23
  • This code is not enough to tell what is wrong Commented Feb 7, 2020 at 8:24
  • I have an object call User in state and a setUser function in mutations, which is works properly. Commented Feb 7, 2020 at 8:25
  • I am trying to add a new object to my array in state and I got an error: TypeError: state.Total.push is not a function . I will provide any additional code if you want, what would it be? Commented Feb 7, 2020 at 8:28

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.