sveltejs / sapper

The next small thing in web development, powered by Svelte
https://sapper.svelte.dev
MIT License
7k stars 434 forks source link

Initialize writable svelte store from sapper preload #1719

Closed MTyson closed 3 years ago

MTyson commented 3 years ago

I want to do something like this:

<script context="module">
    export async function preload() {
        const topicRes = await this.fetch(`topics/all.json`).catch((error) => {
            console.error("ERROR: " + error)
        });
        const serverTopics = await topicRes.json();
        return { serverTopics };
    }
</script>

And then:

<script>
  import { writable } from 'svelte/store';
  export let topics = writable(serverTopics);
</script>

So basically, initialize the topics var with the preload value.

But in the markup:

{JSON.stringify(serverTopics)}
---
{JSON.stringify(topics)}

It shows data in serverTopics but topics is empty.

MTyson commented 3 years ago

Ok, I got it:

{JSON.stringify($topics)}