Search code examples
javascriptsveltesveltekit

How can I load a local json file in sveltekit?


In my SvelteKit app ,I have some data stored in a json file at /static/data.json, an array of objects in json format.

I need to retrieve the data in one of my pages at /src/routes/test/test.svelte. Here's my code at the top of the file.

<script context="module">
    export async function preload() {
        const response = await this.fetch("data.json");
        const jsonRes = await response.json();

        return {
            props: {
                testData: jsonRes,
            },
        };
    }
</script>

<script>
    export let testData;

    console.log(testData);
</script>

I get undefined in the console.

Do you know what I did wrong ? I tried to use load too but it didn't work.


Solution

  • You state that the file is called testData.json, then you should fetch '/testData.json'.

    (In newer versions of SvelteKit the function should be called load and fetch is to be retrieved from the function argument instead of from this.)