Search code examples
vue.jsvuex

Vuex restoring imported Objects after filtering


im struggling again with Vuex and an imported .js file. I have 2 Buttons. The first on will initiate my Store and import a joke.js File with Jokes and load them into the state: jokes:[]. The second Button will delete the first Joke. But if i klick the first Button again, the first Joke will NOT be loaded again! Why????
My Store:

import jokesImportfrom './jokes'

export default {
  state: {
    jokes: []
  },
  mutations: {
    initJokes (state, payload) {
      state.jokes = payload;
    },
    filterJokes (state, deleteJoke) {
      for (let deletions in deleteJoke) {
        state.jokes.filter(element => {
          if (element.id === deleteJoke[deletions]) {
            state.jokes.splice(
              state.jokes.indexOf(element),
              1
            );
          }
        });
      }
    }
  },
  actions: {
    initStore ({ commit }) {
      commit('initJokes', jokesImport);

    },

    storeAnswer: ({ commit }, answer) => {
      commit("filterJokes", answer);
    },
  }

Is there something wrong with my Filter? The Buttons have these both Methods on it:

getJokes() {
  this.$store.dispatch('initStore')
},
checkAnswer(answer){
  this.$store.dispatch("storeAnswer", {
    removeJoke: 1                        //This will remove the Joke with id: 1
  });
}

And the jikes.js look like this:

export default [
    {
        "id": 1,
        "question": "Did you hear about the restaurant on the moon?",
        "answer": "Great food, no atmosphere.",
        "votes": 0
    },
    {
        "id": 2,
        "question": "What do you call a fake noodle",
        "answer": "An Impasta.",
        "votes": 0
    },

Solution

  • You would have to make a deep copy of jokesImport when you are calling initStore.

    If you do not do so, then when you change jokes, it will also affect jokesImport.

    Change your initStore action like this:

    initStore({ commit }) {
        let init = JSON.parse(JSON.stringify(jokesImport)); //making deep copy.
        commit("initJokes", init);
      },
    

    Edit Vuex Store