seyet
seyet

Reputation: 1150

TypeError: Cannot read property 'get' of undefined nuxt

I fetch an api in my api/repository.js from a component through my vuex actions:

//component:
<button @click="click">button</button>

methods:{
  ...mapActions(['click'])
}

//store:
async click({commit}) {
  await this.$repository.liveEvents.genreById().then(data => {
    // commit
  }
}

// api/liveEvents.js:
const baseUrl = process.env.config.baseUrl;

export default ($axios) => ({
   genreById($axios) {
    return $axios.get(`${baseUrl}`)
  }
})

// api/repository.js
import LiveEvents from '~/api/liveEventsApi'

export const repository = ($axios) => ({
  liveEvents: LiveEvents($axios)
})

I have also created a plugin for it:

// plugins/repository.js:
import { repository } from '~/api/Repository.js'

export default (context, inject) => {
  inject('repository', repository(context.$axios))
}

And have added it to my nuxt.config.js:

  plugins: [
    { src: '~plugins/repository.js'}
  ],

However when I click on the button in my component, I get the error Uncaught (in promise) TypeError: Cannot read property 'get' of undefined! I think the issue is api/repository.js somehow doesn't understand $axios. However when I use $axios in my store or directly in my components I don't get any errors! Anyone knows what's wrong here?

Upvotes: 2

Views: 4948

Answers (1)

jonybekov
jonybekov

Reputation: 304

context object doesn't contain $axios instance directly. $axios instance lies inside app object. You have to access to $axios like below:

import { repository } from '~/api/Repository.js'
 
export default ({ app }, inject) => {
  inject('repository', repository(app.$axios))
}

<----------------------- Update after response ------------------------->

In your api/liveEvents.js page you declared function wrong. Here you have to remove $axios argument from genreById function because it might be undefined if you don't pass axios to your function.

export default ($axios) => ({
   genreById($axios) {
             ^^^^^^ - remove it
    return $axios.get(`${baseUrl}`)
  }
})

If you call $axios.$get(...) in the context which $axios is undefined, JS throws error like this TypeError: Cannot read property '$get' of undefined.

Try to review your code and check if you have a syntax error like above.

Upvotes: 1

Related Questions