K
K
Kitaro22018-11-29 09:35:56
Vue.js
Kitaro2, 2018-11-29 09:35:56

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);

If you specify 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 error
Cannot read property 'id' of undefined, console.log(payload);
issues undefined, as I understand it, in this case nothing comes to the state at all.
The same will happen if you pass
context.commit('additem', {item: response.data}); 
export const additem= (state, {item}) => state.items.push(item);

In which direction to dig?) (I use laravel)
[{"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

3 answer(s)
K
Kitaro2, 2018-11-29
@Kitaro2

Helped by user shmatuan
Thanks everyone.

N
nvdfxx, 2018-11-29
@nvdfxx

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);
        })
}

Perhaps it will help, and yet, perhaps you have not noticed, although it is unlikely: one quote 'prod/newitem
methods: {                                  
    submit(){this.$store.dispatch('prod/newitem, this.$data.form);}
}

R
rob3n, 2018-11-29
@rob3n

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 question

Ask a Question

731 491 924 answers to any question