Quantcast
Channel: Active questions tagged svelte - Stack Overflow
Viewing all articles
Browse latest Browse all 1541

Universal rendering skeleton Loading in sveltekit

$
0
0

I'm working on a SvelteKit project where I aim to achieve universal rendering. My goal is to have the first request be server-side rendered (SSR), and then switch to client-side rendering (CSR) for subsequent navigation. However, I'm encountering a problem that I can't seem to resolve.

The Problem:

When navigating from one page to another (e.g., from Home to Products), the navigation doesn't occur until the data for the target page is fully fetched. Ideally, I want the target page to load immediately and display a loader for individual components while the data is being fetched. This way, the user isn't stuck waiting for the entire page to load before the navigation occurs.

I've tried implementing this using Svelte's {#await ...} blocks in my component, but I'm facing a dilemma:

Using await inside the load function:SSR works fine, but the page navigation is delayed until the data is fetched.

Skipping await in the load function:Navigation occurs immediately, but SSR breaks.

My Setup:

Here's a simplified version of what I'm working with:

// +page.svelte

<script lang="ts">  let { data } = $props();</script><h1>TODOS</h1>{#await data.todos}  Loading ...{:then todos}  {#each todos as todo}<div>{todo.todo}</div>  {/each}{/await}

// +page.ts

type Todo = {  id: number;  todo: string;  completed: boolean;  userId: number;};export async function load({ fetch }) {  const getTodos = () =>    fetch('https://dummyjson.com/todos')      .then(r => r.json())      .then((r): { todos: Todo[] } => r.todos);  return {    todos: getTodos(), // await getTodos()  };}

// /products/+page.svelte

<script lang="ts">  let { data } = $props();</script><h1>Products</h1>{#await data.products}  Loading ...{:then products}  {#each products as product}<div>{product.title}</div>  {/each}{/await}

// /products/+page.ts

type Product = {  id: number;  title: string;};export async function load({ fetch }) {  const getProducts = () =>    fetch('https://dummyjson.com/products')      .then(r => r.json())      .then(r => r.products as Product[]);  return {    products: getProducts(), // await getProducts(),  };}

What I'm Looking For:

Has anyone managed to solve this problem, or is there a better approach that I'm missing? I'd love to get some advice or examples on how to properly implement universal rendering with SSR on the first request and smooth client-side navigation with individual component loaders afterward.

P.S i tried browser ? getTodos() : await getTodos()but I'm getting hydration mismatch error


Viewing all articles
Browse latest Browse all 1541

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>