How to use SSR with Stores on SvelteKit
Asked Answered
B

1

7

I am new to sveltekit and svelte in general, and I am trying to load data from an API to the stores, here is how I am doing it

    export const load = async ({ fetch }) => {
        const data = get(dataStore);

        if (browser && data) {
            return { status: 200 };
        }

        const res = await fetch('/data.json', { credentials: 'include', mode: 'cors' });
        const data = await res.json();

        if (browser) {
            dataStore.set(data);
        }

        return { status: res.status };
    };

my question is what is best approach to load data on SSR to the FE stores ?

Bellay answered 9/3, 2022 at 16:25 Comment(2)
Is using stores a requirement? I find the best approach to be returning the data from the fetch as props in the load function.Headliner
@BobFanger thank you! you just unconfused me and pointed out the obvious.Downtrodden
C
1

One possible approach is using the server's load function into a *.layout.svelte. That layout will receive the data as props and then you can keep this data in a store to propagate through the application.

I recommend doing it in fewer scenarios where you have many components at same page, sharing and modifying the same data. Otherwise, you don't need store at all.

Celebrity answered 24/12, 2022 at 22:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.