0
votes

Hi I’m new to vue and vuex.

I have posted some data in store, and need to modify a nested array property of it depending on user selection. I am trying to use ‘actions’ in my store, but when I use ‘this.$store.dispatch’ I get ‘Uncaught TypeError: state.storyInfo.push is not a function’. if I use a ‘this.$store.commit’ to commit directly to ‘mutations’, I get the original state not modified.

This is the data in my state:

{
  "id": 1,
  "title": "Story title",
  "episodes": [
    {
      "id": 1,
      "title": "Episode 1"
    },
    {
      "id": 2,
      "title": "Episode 2"
    },
    {
      "id": 3,
      "title": "Episode 3"
    }
  ]
}

If for example the user selects episode with id = 2, I would like the state to become:

{
  "id": 1,
  "title": "Story title",
  "episodes": [
    {
      "id": 2,
      "title": "Episode 2"
    }
  ]
}

my store.js looks like this:

export const store = new Vuex.Store({
  state: {
    storyInfo: null
  },
  mutations: {
    setStory (state, payload) {
      state.storyInfo = payload
    },
    addInfoToStory (state, payload) {
      const data = this.state.episodes
      state.storyInfo.push(data)
    }
  },
  actions: {
    addToStory (infoToAdd, payload) {
      infoToAdd.commit('addInfoToStory', payload)
    }
  },
  getters: {
    selectedStoryInfo: state => state.storyInfo
  }
})

The methods in the component looks like this:

methods: {
  addSelectedEpisode () {
    this.$store.commit('addToStory', this.episode) // <- here if I use dispatch I get the error and no result
  },
  redirectTo () {
    this.$router.push({name: 'Read'})
  }
}

I have also tried to adapt some TODOs example found online, but nothing I do seems to work.

What am I doing wrong?

2

2 Answers

0
votes

At store.js you are initializing storeInfo as null.

push is a method that works only for arrays, so it won't work on a null variable.

Try to set storeInfo as an empty array instead:

export const store = new Vuex.Store({
  state: {
    storyInfo: []
  },

  ...
0
votes

Posting my own solution. In Store, replace 'addInfoToStory' mutation with the story path of what needs to change:

addInfoToStory (state, payload) {
  state.storyInfo.episodes = payload
}

this will modify only that property in state.