How to acces "this" in Nuxt's fetch() hook if "context" is passed?

Viewed 553

Usually we can access "this" in fetch() hook and use component's methods or data.

But how to access "this" if context is passed to fetch() hook?

For example, I want to call component's method inside fetch() hook which makes request to API and if nothing found throw error in maybe Nuxtish way

I tried to use context.app.fetchKitties instead of this.fetchKitties, but seems like this is stored in other context's property I guess

fetch (context) {
  this.fetchKitties({ color: context.route.params.color })
    .catch(err => {
      if(err.status === 404) context.error({ message: "No kitty is found!", statusCode: 404})
    }
},
1 Answers

If you pass a context, you'll end-up with the old fetch.
You can use this directly into the fetch() hook, hence no need to pass the context as an argument (because you can access it directly).

For more info, read my comment on the github issue here: https://github.com/nuxt/nuxt.js/issues/9564#issuecomment-882954272

Hence, use this.$route if you want to access it in fetch().

Related