single-page-applicationsveltekit

SvelteKit: Pass Data From +Layout.svelte To +page.svelte SPA (static) application


I'm struggling with the latest version of SvelteKit, the docs available only works with SSR, and I'm developing a SPA (static page), so, what is the way to pass data from my +layout.svelte to +page.svelte ?.

The documentation says that with load function from +page.js (I've already set export const ssr=false, and I understood that +page.js is for SSR), but that doesn't work in SPA mode, and if I have the load function from the layout it's seems not to work.

Additionaly I want to trigger a function from my +page.svelte that is in the layout page.

Any ideas?

Here is what I tried :

<!-- +layout.svelte -->
<script>
    export function load() {
        return {
            data: { title: 'default title' }
        };
    }
    export let data;
</script>

//+page.svelte
<script>
    export let data;
    console.log(data.title); //undefined
</script>

The documentation says not to use : <script context="module">, and I don't want to use the store because I think there must be a better way.


Solution

  • Load functions belong in the accompanying files +layout.js/ts, not on the page. They also do not return a property data, everything returned is the data. See the docs.

    If SSR is disabled, you can event return a store that could be modified from the page.

    To get a store from the data so it can be used with $-syntax, the data property can be destructured on the page:

    export let data;
    $: ({ title } = data);
    

    You could also create a store and set it as a context in the layout. Pages then can get said context and interact with it. This allows two-way interaction.

    Using a store is necessary if the contents require reactivity (i.e. are changed) and the page or layout needs to update.