D
D
Denis Labutin2018-10-02 17:20:19
Vue.js
Denis Labutin, 2018-10-02 17:20:19

Vuex how to properly fetch data via REST API?

Good afternoon, such a question, Google did not find anything sensible.
There is a
List of elements I get the whole list into action through axios and cause a mutation that sets the state of lists.
[ {id: 12, name: "12"}, {id: 43, name: "43"}]

const actions = {
    getList({commit}){
        let list = api.getList();
        commit('setList', list);
    }
}

const mutations = {
    setList(state, list){
        state.list = list;
    }
}

And after in the component I call
created () {
    	this.$store.dispatch('getList');
},
computed: {
    list(){
      return this.$store.state.list;
    }
  },

So I have a list of elements in the state, and I can change them and change them.
Now I have another component view item'a from list.
For good, you need to make an additional getItem (id) request.
I specified the getItem (id) request in vuex'e in the getter, so as not to iterate over the array on the client.
const getters = {
 	getItemById: state => id => {
    	return api.getItem(id);
  	}
 }

1.Is the approach correct?
2. Is the state preserved if I change the item? When item'a is changed, the state of the list will not change, as I understand it, that is, in the action'e you will have to change the state too? Or just make a request to update the list when changing?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Shelemetiev, 2018-10-03
@zoroda

1. I don't see anything incorrect in this approach.
2. It is better to change item through mutation/action. Use Vue.set otherwise Vue won't track changes to the parent list.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question