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 by private message.

Hello,

I dived into your component code and found, where you need to modify it:

  1. You need to initialise post in data as an empty array, not as an object.
  2. You need to use this keyword when using fetch hooks.
  3. In templating, you don't need to use this keyword.

Code snippet:-

 <template>
    <div>{{posts}}</div>
      <section v-for="post in posts" :key="post.id" v-bind:post="post" class="blog-post">
         <h2>
           {{ $prismic.asText(post.data.title) }}
        </h2>
        </section>
</template>

<script>
export default {  
  data: function() {
     return {
        posts:[]
    }
  },
  async fetch() {
    this.posts = (await this.$prismic.api.query(
      this.$prismic.predicates.at("document.type", "page"),
      { orderings: "[my.post.date desc]" }
    )).results
},

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

Thanks,
Priyanka

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.