0

During runtime, the object payload I pass as a secondary parameter to my Vuex mutation method is always undefined. Both my Vuex and component files are written in TypeScript.

My index.ts file for my Vuex store looks like this (note that I'm using the modular store approach):

import Profile from '@/models/Profile'
import { createStore } from 'vuex'

const userModule = {
  state: () => ({
    profile: Profile
  }),
  mutations: {
    setProfile (state:any, profile: Profile) {
      // `state` is the local module state
      state.profile = profile //**RUNTIME ERROR: profile = undefined
    } 
  },
  getters: {
    getProfile (state:any) {
      return state.profile
    }
  }
}

export default createStore({
  state: {
  },
  mutations: {
  },
  actions: {
  },
  modules: {
    user: userModule
  }
})

I commit to the store from my Vue component's methods like this:

 <script lang="ts">
 export default Vue.extend({
    methods: {
      fetchProfile() {
        axios
            .get("/getUser", requestHeader)
            .then((profileResponse: Profile) => {
              //store profile in Vue Store
              store.commit('setProfile', profileResponse)
            })
      }
    }
 })
 </script>

What am I doing wrong?

1
  • 1
    Is profileResponse definitely not undefined when you commit it? Commented Dec 22, 2020 at 3:31

1 Answer 1

1

The axios.get().then() callback has a parameter of type AxiosResponse, which wraps the actual response in its data property. The code should look like this:

import axios, { AxiosResponse } from 'axios'

axios.get(/*...*/)
  .then((response: AxiosResponse) => {
    const profileResponse = response.data
    store.commit('setProfile', profileResponse)
  })
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.