ConsoleTVs / sswr

🔥 Svelte stale while revalidate (SWR) data fetching strategy
MIT License
243 stars 12 forks source link

Server side rendering SvelteKit example does not work #34

Open khromov opened 2 years ago

khromov commented 2 years ago

The current SSR example from the readme does not work. I have submitted a working SSR example in https://github.com/ConsoleTVs/sswr/pull/32 and I think that is the only way to have working SSR. ("Working" in this case means the rendered data is present in the HTML response from the server.)

Demo

You can see that "undefined" flashes on the screen before the data loads: Animation

Repro (code from readme)

<script lang="ts" context="module">
  import type { Load } from '@sveltejs/kit';

  const url = 'https://jsonplaceholder.typicode.com/posts';

  export const load: Load = async ({ fetch }) => {
    const response = await fetch(url);

    return {
      props: {
        initialData: await response.json()
      }
    };
  };
</script>

<script lang="ts">
  import { useSWR } from 'sswr';

  interface Post {
    id: number;
    title: string;
    body: string;
  }

  export let initialData: Post[];

  const { data: posts } = useSWR<Post[]>(url, {
    initialData,
    revalidateOnStart: false
  });
</script>

<pre>{JSON.stringify($posts)}</pre>

Misc

I have also tried an alternative approach with data fetching through a Page Endpoint but that has the same problem where the value is undefined at the start.