1

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?

1 Answer 1

5

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);
    })
}
Sign up to request clarification or add additional context in comments.

1 Comment

wow so simple... though if I set that after axios it will actually wait till its finished and then continue. Thnaks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.