Search code examples
sveltesapper

How to preload data in Sapper app from Prismic API


In my Sapper App I want to preload from Prismic API using their SDK ('prismic-javascript)

I followed the docs for preloading content. Yet the docs only provide the preloading through the this.fetch function. I want to connect to my Prismic repository with the Prismic SDK. But it doesn't give me back any data at all.

I also tried the this.fetch method with JSONplaceholder. That just works fine. Even requiring the Prismic-SDK the "old way" doesn't work:

var Prismic = require("prismic-javascript")

So this is what my code looks like:

<script context="module">
  import Prismic from "prismic-javascript";
  const apiEndpoint = "https://my-repository.cdn.prismic.io/api/v2";

  export async function preload(page, session) {
    const api = await Prismic.getApi(apiEndpoint, { req });
    const data = await api.getSingle("portfolio");
    return { data };
  }
</script>

This code should populate the data variable with the API-data. But it doesn't. Is there anyone who could help me out here? Thanks!


Solution

  • This one works if you don't need the req object from Prismic:

      import Prismic from "prismic-javascript";
      const apiEndpoint = "https://my-repository.cdn.prismic.io/api/v2";
    
      export async function preload({ params, query }) {
        const api = await Prismic.getApi(apiEndpoint);
        const data = await api.getSingle("portfolio");
    
        return { data };
      }
    </script>