Search code examples
vue.jsaxiosvuexnuxt.jsvuex-modules

Axios Get with Header in Vuex - NUXTJS


I get a issues with Axios Get with Header in Vuex - VueJS, hope you guys help me.

Pages:

<template>
<div class="temp">{{users.info}}</div>
</template>

<script>
data: function () {
    return {
      config: {
        'headers': {'Authorization': 'JWT ' + this.$store.state.token}
      }
    }
  },
fetch ({ store, params }) {
    return store.dispatch('getProfile', params, this.config)
  },
</script>

Vuex Modules:

import api from '~/plugins/axios'

const state = () => {
  return {
    info: null
  }
}

const actions = {
  getProfile ({commit}, params, config) {
    return new Promise((resolve, reject) => {
      api.get(`/users/${params.username}/`, config)
      .then(response => {
        commit('GET_USER_DETAIL', response.data)
        resolve(response.data)
      },
      response => {
        reject(response.data)
      })
    })
  }
}
const getters = {}

const mutations = {
  GET_USER_DETAIL (state, info) {
    state.info = info
  }
}

export default {
  state,
  actions,
  getters,
  mutations
}

Issues: config in Vuex module is not defined.

I think Im wrong with something hope your help. Thanks in advance!


Solution

  • Actions in Vuex can't contain more than one parameter. Group up your params into a single object, like so:

    return store.dispatch('getProfile', { params: params, config: this.config })
    

    Then access from your action like so:

    getProfile ({commit}, obj) {
      var params = obj.params
      var config = obj.config
      /* ... */
    }
    

    If you look at the section Dispatching Actions in the docs it shows the correct way to pass params.