How to initialize svelte kit application with globally shared data from db

Viewed 12

I have e language table in my db where it has all the words/sentences of my website in different language. I don't want to call API for every single word/sentence in the website. What is the best approach in svelte kit to get all the data from that table before my website initializes and then store them in such way that all my pages and component can access them? Also that data need to be updated if the user changes the language of the website.

1 Answers

You could define a server load function at the top level layout and pass on that data to a store which can be provided as a context to every page using the layout.

E.g.

// +layout.server.ts
import type { LayoutServerLoad } from './$types';

const fakeData = {
    title: 'SvelteKit',
    description: 'A new way to build web applications',
};

export const load: LayoutServerLoad = async () => {
    // Fetch localization data here

    return {
        localization: fakeData,
    };
};
<!-- +layout.svelte -->
<script lang="ts">
    import { setContext } from 'svelte';

    export let data: { localization: any };

    setContext('localization', writable(data.localization));
</script>

Usage in a page:

<script lang="ts">
    import { getContext } from 'svelte';
    import type { Writable } from 'svelte/store';

    const localization = getContext<Writable<any>>('localization');
</script>

{$localization.title}

The key for the context and getting/setting the context could be extracted to constants/extra functions. If the language has to be updated on the fly, you just have to fetch the new data and set the store content.

Related