#svelte #javascript #frontend

Day 12: Loading Data

Welcome to Day 12. Components need data.

In SvelteKit, we fetch data before the component renders, often on the server.

+page.server.ts

Alongside your +page.svelte, create +page.server.ts.

// src/routes/blog/+page.server.ts
export async function load() {
  return {
    posts: [
      { title: "First Post", id: 1 },
      { title: "Second Post", id: 2 }
    ]
  };
}

Consuming Data

Your page receives this data via the data prop.

<!-- src/routes/blog/+page.svelte -->
<script lang="ts">
  let { data } = $props();
</script>

<h1>Blog</h1>
<ul>
  {#each data.posts as post}
    <li>{post.title}</li>
  {/each}
</ul>

This functions identically with SSR (user sees HTML with data) and CSR (data is fetched as JSON during navigation).

Route Parameters

For /blog/[slug]:

// src/routes/blog/[slug]/+page.server.ts
export async function load({ params }) {
  // fetch content based on params.slug
  return {
    title: `Title for ${params.slug}`,
    content: "..."
  };
}

Challenge for Day 12

  1. Create a route /products.
  2. In load, return a list of dummy products.
  3. Display them.
  4. Create a route /products/[id].
  5. In load, use params.id to find the product and return it.

Solution:

// +page.server.ts (products/[id])
export function load({ params }) {
  const product = db.find(p => p.id === params.id);
  if (!product) throw error(404, 'Not found');
  return { product };
}

Tomorrow: Form Actions.