0
0
Svelteframework~30 mins

Page load functions (+page.js) in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Page Load Functions with +page.js in SvelteKit
📖 Scenario: You are building a simple SvelteKit page that shows a list of books with their authors. The data will be loaded using a +page.js file to separate data fetching from the page component.
🎯 Goal: Create a SvelteKit page that loads a list of books using a +page.js load function and displays them on the page.
📋 What You'll Learn
Create a +page.js file with a load function that returns the books data.
Use a constant variable to hold the books data inside +page.js.
In the Svelte page component, access the loaded data using the data prop.
Display the list of books with their titles and authors in the page component.
💡 Why This Matters
🌍 Real World
Separating data loading logic into +page.js files helps keep SvelteKit pages clean and organized. This pattern is common in real web apps to fetch data before rendering.
💼 Career
Understanding page load functions is essential for building scalable SvelteKit applications that fetch and display data efficiently.
Progress0 / 4 steps
1
Create the books data in +page.js
Create a constant variable called books in +page.js with this exact array of objects: { title: 'The Hobbit', author: 'J.R.R. Tolkien' }, { title: '1984', author: 'George Orwell' }, and { title: 'Pride and Prejudice', author: 'Jane Austen' }.
Svelte
Hint

Use export const books = [...] to create the data array in +page.js.

2
Add the load function to return the books data
Add an exported async function called load in +page.js that returns an object with a property books set to the books array.
Svelte
Hint

Define export async function load() and return { books }.

3
Access the loaded books data in the Svelte page
In the Svelte page component, use the data prop to access the loaded books array. Use a {#each} block with book as the iterator variable to loop over data.books.
Svelte
Hint

Use export let data; and a {#each data.books as book} block to display the list.

4
Complete the page with semantic HTML and accessibility
Wrap the books list in a <main> element with an <h1> heading that says Book List. Ensure the list uses a semantic <ul> with <li> items.
Svelte
Hint

Use semantic HTML: wrap the list in <main> and add an <h1> heading.