asyncData with prismic api query in a Slice (Nuxt.js)

Hi!

I have a Custom Type Project.
In this Custom Type, i have a boolean field highligh.

My Homepage is built on a Custom Type Page. This Custom Type may contain a Slice "Highligh Projects".

On this slice, I would like to get all the projects with the highlight attribute set to true.

However, I have the impression that you can't make a Prismic API request in a Slice. Am I wrong?

My slice/ListofProjects file:

<template>
  <section class="section container listofprojects">
    <PrismicRichText :field="slice.primary.title" class="title" />

    <CasClients :projects="clients" />

  </section>
</template>

<script>
import { getSliceComponentProps } from "@prismicio/vue/components";

export default {
  name: "ListofProjects",
  // The array passed to `getSliceComponentProps` is purely optional and acts as a visual hint for you
  props: getSliceComponentProps(["slice", "index", "slices", "context"]),
  async fetch({ $prismic, params, error }) {
    const { results: clients } = await $prismic.api.query(
      $prismic.predicate.at('my.client.highlight', true)
    )
    return {
      clients
    }
  }
}
</script>

The clients var is unknowned :frowning:

I tried this too:

data(){
    return{
      clients: []
    }
  },
  async fetch() {
    this.clients = await this.$prismic.api.query(
      $prismic.predicate.at('my.client.mea', true)
    )
  }

Thanks a lot!
Vincent

Hey @Vincent07, in this case, you will need to do a query using GraphQuery to first get the project's highlight Boolean field from the Content Relationship field in the highlight Slice in the page document and then filter the result on the front-end, so you can determine if highlight is true or false.

So we agree: i can't use asyncData() or fetch() in a Slice file?

The methods will retrieve data at the document level. So the Slice content will be included in the response as well.

1 Like