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

14,871

Solution 1

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.

Solution 2

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');
    }
}

Solution 3

Here is straight use of axios module in nuxt.js

  1. Components

asyncData

async asyncData({ $axios }) {
  const ip = await $axios.$get('http://icanhazip.com')
  ....
}

methods/created/mounted/etc

methods: {
  async fetchSomething() {
    const ip = await this.$axios.$get('http://icanhazip.com')
    ....
  }
}
  1. Store Actions
{
  actions: {
    async getIP ({ commit }) {
      const ip = await this.$axios.$get('http://icanhazip.com')
      .......
    }
  }
}
  1. Shortcuts
// Normal usage with axios
let data = (await $axios.get('...')).data

// Fetch Style
let data = await $axios.$get('...')

here up are the ways you can use to access nuxt.js $axios module

keep in mind that this was the new v5.12.3 release when this answer was made

also check this axios module link from nuxt js website

Share:
14,871
xKxAxKx
Author by

xKxAxKx

Engineer

Updated on June 04, 2022

Comments

  • xKxAxKx
    xKxAxKx almost 2 years

    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?