Fetching data from Sanity in lib/ files or __layout.svelte for Sveltekit + Sanity integration

Viewed 64

I can't seem to fetch GROQ results within a __layout.svelte file or even within libs/Footer.svelte for example

GROQ (found in index.js):

export async function get() {
  const data = await client.fetch(/* groq */ `{

    "settings": *[_type == "siteSettings"][0]
  }
 
}

I tried:

<script>
   export let settings
</script>

{settings}

The above code obviously works within Index.svelte, but can't seem to pass through {settings} to the __layout.svelte file?

1 Answers

With SvelteKit routes are defined by having a .svelte file for them, if you also have .js file with the same name, this will act as a page endpoint.

Like in your case where you have index.js and index.svelte. When visiting the path / the javascript file will provider the svelte file with some values (if you have a get defined of course)

As of current (26.07.2022) there is no equivalent way to do this with layouts, but there is an issue for it here https://github.com/sveltejs/kit/issues/4274.

What you will have to do to load data in __layout.svelte is to manually add the loading yourself.

<script context="module">
   export async function load({ fetch }) {
      const settings = await fetch('/settings').then(res => res.json());
      return {
        props: {
          settings
        }
      }
    }
</script>
<script>
  export let settings;
</script>

The above code assumes you have another file called settings.js with a GET function defined.

Often you will see that endpoints that are not directly connected have a suffix indicating the type of content they return: settings.json.js. If you follow that convention you have to do fetch('/settings.json') of course.

Related