Answer the question
In order to leave comments, you need to log in
VueJs, Vuex how to pass response from server to state?
Good afternoon, not long ago I started learning vuejs and wanted to try vuex, and I ran into the problem of sending a response from the server to the state, I found several English-language topics on the Internet, but I couldn’t figure out what was what ...
Problem: you need to pass a new item to the component , but an empty string is added from state without any data, when the page is reloaded, the data is displayed.
Component:
methods: {
submit(){this.$store.dispatch('prod/newitem', this.$data.form);}
}
Action:
export const newitem= (context, payload) => {
axios.post('/api/product/add', payload)
.then((response) => {
context.commit('additem', response.data);
})}
Mutation:
export const additem= (state, payload) => state.items.push(payload);
context.commit('additem', response.data.add);
and do not change anything else in the code above, the component will not be updated and will generate an errorCannot read property 'id' of undefined, console.log(payload);
issues undefined
, as I understand it, in this case nothing comes to the state at all. context.commit('additem', {item: response.data});
export const additem= (state, {item}) => state.items.push(item);
[{"name":"test","num":"12412","desc":"test", "updated_at":"2018-11-29 09:44:54","created_at":"2018-11-29 09:44:54","id":58}]
answer
Answer the question
In order to leave comments, you need to log in
commit in actions is better to pass through {commit}, and not context, and use
export const newitem= ({commit}, payload) => {
axios.post('/api/product/add', payload)
.then((response) => {
commit('additem', response.data);
})
}
methods: {
submit(){this.$store.dispatch('prod/newitem, this.$data.form);}
}
In fact, you receive an array and it can be longer than one object, you are doing everything right when you save such a response from the server to the State, you just need to render an array, and now you are more likely to access an object in the template without v-for
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question