1

I'm having problems dealing with async data in Nuxt dynamic routes.

Example of folder structure,

enter image description here

My async data

async asyncData({context, error, req}) {
  try {
    const api = await Prismic.getApi(PrismicConfig.apiEndpoint, {req})

    let document = []
      const result = await api.getByUID('news', this.$route.params.slug)
      document = result.results

    return {
      document,
      documentId: result.id,
    }
  } catch (e) {
      error({ statusCode: 404, message: 'Page not found' })
    }
}, 

So I always end up in 404 page not found. I tried with other examples of async data that works ok on normal "non dynamic routes" an it also returns 404.

I'm assuming that this is problem related with Async data Nuxt has with components as well and that this is something Nuxt will handle in version 3.0?

But until then I would appreciate if you could help me out with this, I need to make this work somehow.

I'm using Prismic as headless API cms.

Adil
  • 240
  • 1
  • 6
  • 19
Goran
  • 708
  • 7
  • 20

1 Answers1

4

the issue here is that you cannot use 'this' inside an async function. The way to accomplish what you need is to use the 'params' context provided by nuxt https://nuxtjs.org/api/context this will allow you to pass the uid to the query. You can see how to do this below.

async asyncData({ params, error, req }) {
  try{
    // Query to get API object
    const api = await Prismic.getApi(PrismicConfig.apiEndpoint, {req})

    // Query to get content by 'news' type and whatever the uid for the document is
    const result = await api.getByUID("news", params.uid)

    // Returns data to be used in template
    return {
      document: result.data,
      documentId: result.id,
    }
  } catch (e) {
    // Returns error page
    error({ statusCode: 404, message: 'Page not found' })
  }
},

Also for your file structure you don't need the _slug folder you can just rename the index.vue inside the news folder as _uid.vue and have : news/ _uid.vue

You can see the full blog we made over at Prismic here: https://user-guides.prismic.io/en/articles/2802125-create-a-sample-blog-with-prismic-and-nuxt

Bruja
  • 368
  • 2
  • 10
Phil Snow
  • 124
  • 2