Search code examples
typescriptvue.jsvuexvuex-modules

Vuex + Typescript: Mutation Object Payloads are Always Undefined


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?


Solution

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