Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use `$axios` in utility function in Vuex of Nuxt.js

I am configuring VUEX of Nuxt.js as follows.

store
├── README.md
├── posts
│   ├── actions.js
│   ├── getters.js
│   ├── index.js
│   ├── mutations.js
│   └── utils
│       └── getPostById.js
└── index.js

I added @nuxtjs/axios to modules in nuxt.config.js and make it possible to use this.$axios.$get in actions.
However, you can not use A in store/posts/utils/getPostById.js.
An error of Cannot read property '$axios' of undefined will occur.

Each code is described as follows.

・ store/index.js

import Vuex from 'vuex'
import postsModule from './posts'

new Vuex.Store({
  modules: {
    posts: postsModule
  }
})

・store/posts/index.js

import actions from './actions'
import getters from './getters'
import mutations from './mutations'

export const state = () => ({
  posts: [],
  post: {}
})

export default {
  namespaced: true,
  state,
  actions,
  getters,
  mutations
}

・ store/posts/actions.js

import getPostById from './utils/getPostById'

export default {
  async fetchPost({ commit }, count = 10) {
    const params = { count: count }
    // Here `$axios` can be used normally
    const result = await this.$axios.$get("ApiUrl")
    commit('setPosts', result)
  },
  async fetchPostById({ commit }, category_ids, count = 10) {
    const topCommunities = {}
    const result = await getPostById(id)
    commit('setPost', result)
  }
}

・ store/posts/utils/getPostById.js

export default async function(post_id) {
  // Here `$axios` can not use
  const result = await this.$axios.$get(`${ApiUrl}/${post_id}`)
  return result
}

How can I use this.$axios.$get inside getPostById.js?

like image 564
xKxAxKx Avatar asked Feb 07 '19 09:02

xKxAxKx


2 Answers

Quite a few things have changed since the question was posted. You can now access the $axios utility in the store via this.$axios. The nuxt plugin uses inject to make the $axios object available in the store as described here.

As an example:

export const actions = {
    async fetchUser () {
        let user = await this.$axios.$get('/me');
    }
}
like image 83
Cristian Calara Avatar answered Nov 27 '22 19:11

Cristian Calara


To the best of my knowledge, you can only access axios in your nuxtServerInit() under actions in your store like so

async nuxtServerInit ({ commit }, { $axios }) {
  const ip = await $axios.$get('http://icanhazip.com')
  commit('SET_IP', ip)
}

Check this page https://axios.nuxtjs.org/usage for more information on how to use axios in NuxtJS projects.

like image 32
Jalasem Avatar answered Nov 27 '22 18:11

Jalasem