Skip to content
Advertisement

How to access Nuxt context inside of fetch() hook?

I want to access the props inside the async fetch() but I’m also using async fetch(context). So, I’m not sure how to access the props.

Advertisement

Answer

In Nuxt 2, you have 2 fetch hooks.

The old one, before Nuxt 2.12, fetch(context) which acts a lot like asyncData. It’s executed before the component creation, so you don’t have access to it (data, props, options… nothing).
This one is deprecated, use asyncData instead.

The new one, from Nuxt 2.12, fetch() (with no parameters). It’s executed at the same time as the created() hook. It has access to the component’s context (props, data, etc.).

fetch(context) {
  // "this" doesn't exists
  // context is the Vue global context
}

fetch() {
  this.myProp // "this" exists and have access to props
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement