Using prismic/nuxt as a component for blog post previews

Hello,

The way I have currently setup Nuxt/Prismic works, but I was wondering if it was possible to Query the API not using async. I want to have a preview of the latest blog posts in the home page, and a way of doing that hassle free would be to do it as a component, which doesn't run async, is that possible?

Hello,

Thanks for reaching out us.

You can try to use fetch hooks under components. It is called during server-side rendering after the component instance is created. You can find more details here and here.

Note: Please make sure you are using Nuxt 2.12 and later.

I hope this answers your question. Let me know if you have doubt.

Thanks,
Priyanka

Hello,

I keep getting this issue, "Error in fetch(): ReferenceError: $prismic is not defined" when using the following code. Prismic is already installed in the current Nuxt environment (and using async in pages does work, but as mentioned I want to use it as a component), I keep searching to see whether I missed something, but I'm not finding anything.

async fetch() {
this.posts = await this.$prismic.api.query(
$prismic.predicates.at("document.type", "post"),
{ orderings: "[my.post.date desc]" }
);
},

Can you please try by adding "this" keyword in the query like:

async fetch() {
  this.posts = await this.$prismic.api.query(
    this.$prismic.predicates.at("document.type", "post"),
    { orderings: "[my.post.date desc]" }
  );
},

Give this a try and let me know if you have any other doubt.

Tried as suggested, got the following error message :frowning:.

What are you getting in "this.posts". I'd be happy to troubleshoot it. For this, I need your code and Prismic repo url. If you don't prefer to send it publicly, send me private message.