D
D
DiseaseC2020-02-26 13:36:07
Vue.js
DiseaseC, 2020-02-26 13:36:07

Vue/Vuex - How to correctly change the state of a component in mutations?

I need to parse the API using vue and vuex
There is a request from the component:
this.$store.dispatch('FETCH_STORIES');
Action:

FETCH_STORIES: ({ commit }) => {
        axios.get("http://hn.algolia.com/api/v1/search?tags=front_page")
            .then(response => {
                let result = response.data;
                commit("APPEND_STORY", result);
            })
},

Mutation:
APPEND_STORY: (state, article) => {
        state.stories.push(article);
    },

The repository looks like this:
state: {
    stories: [],
}

Due to the push method in mutations, the data in the template got wrapped in an array (there was only one element inside), and in order to access the data, it was necessary to loop through the array. I need to get rid of this cycle, which means I need to get rid of both the array and the push method.
I try something like this, but the data does not come
APPEND_STORY: (state, payload) => {
        state.stories = payload;
    },

How can this be fixed?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Anton, 2020-02-26
@DiseaseC

To get rid of the cycle, you can make an object or a map with the id key instead of an array. Why is there crap in the store - you need to look at the code. The mutation is generally correct.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question