2

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.

CC BY-SA 4.0

2 Answers 2

1

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.

CC BY-SA 4.0
5
0

in SPA you can not access *.server.js file but you can use layout.js/page.js

   //layout.js/page.js 

    export function load() {
            return {
                title: 'default title' //just return want you need
            };
        }
    

    //page.svelte

    <script>
        export let data;
        console.log(data.title); //default title
    </script>
CC BY-SA 4.0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.