Reputation: 620
In this example, I'm using axios to fetch some data for me and then I need to pass these values and store it in Vuex
vue file with axios request:
<script>
export default {
data: function () {
return {
userData: {},
login: {
username: '',
password: '',
},
}
},
computed: {
loggedInUser() {
return this.$store.state.loggedInUser;
}
},
methods: {
handleLoginFormSubmit() {
// send axios request to controller and from controller to gRPC
axios.post('/loginUser', this.login)
.then((response) => {
this.userData = JSON.parse(response.data[0]);
})
// set loggedInUser info to vuex store
this.$store.dispatch('loginUser',this.userData);
}
},
}
</script>
when I inspect userData object is there with all info that I need now I have store.js file that should pass that userData and save it in Store but I always get empty object inside
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
loggedInUser: {
firstName: '',
lastName: '',
email: '',
uuid: '',
}
},
getters: {
loggedUser(state){
return state.loggedInUser;
}
},
mutations: {
loginUser: (state, payload) => {
state.loggedInUser.firstName = payload;
state.loggedInUser.lastName = 1;
state.loggedInUser.email = 1;
state.loggedInUser.uuid = 1;
}
},
actions: {
loginUser: (context, payload) => {
setTimeout(function () {
console.log(payload);
context.commit('loginUser', payload)
}, 3000)
}
}
});
my mutation looks like this
type:"loginUser"
payload:Object (empty)
where did I do something wrong?
Upvotes: 1
Views: 2036
Reputation: 82459
You dispatch before the data has returned. Move the dispatch into the callback.
handleLoginFormSubmit() {
// send axios request to controller and from controller to gRPC
axios.post('/loginUser', this.login)
.then((response) => {
this.userData = JSON.parse(response.data[0]);
this.$store.dispatch('loginUser',this.userData);
})
}
Upvotes: 5