Here's what you'll build: Mrs. Sri's shopping list for the market, inside the app of Mrs. Sri's stall that already has a menu page, a cart count in the header, and an order form. This project uses many lessons at once: routes and a layout from SvelteKit, data from load, a store for the cart, a form action for orders, and components with {#each}, bind:, and the $state and $derived runes.
Picture Mrs. Sri's stall on its first day open. You've already set up the kitchen, the display case, the cashier and the signboard one at a time. Now they're all fitted into one building and used together. The building is the project folder, its rooms are routes, its signboard is the layout, and the notebook every room reads is a store.
The map of the stall project
You've written all these files in earlier lessons. In one project, they meet:
| File | What it holds | From the lesson |
|---|---|---|
src/lib/menu.js |
the menu data, a pretend database | Load Data |
src/lib/cart.js |
a custom store: add, remove, clear |
Custom Stores |
src/routes/+layout.svelte |
header, nav, cart count, {@render children()} |
Routing, Stores |
src/routes/menu/+page.js and +page.svelte |
the menu load, Add buttons into the cart |
Load Data, Events |
src/routes/order/+page.server.js and +page.svelte |
the order form with fail and redirect |
Form Actions |
src/routes/shopping/+page.svelte |
Mrs. Sri's shopping list for the market | this lesson |
The layout reads the store, so the cart count shows on every page:
<!-- src/routes/+layout.svelte -->
<script>
import { cart } from "#lib/cart.js"
let { children } = $props()
</script>
<header>
<h1>Mrs. Sri's Stall</h1>
<nav>
<a href="/menu">Menu</a>
<a href="/shopping">Shopping</a>
</nav>
<p>Items in cart: {$cart.length}</p>
</header>
{@render children()}
<!-- src/routes/menu/+page.svelte -->
<script>
import { cart } from "#lib/cart.js"
let { data } = $props()
</script>
<h2>Menu</h2>
<ul>
{#each data.menu as m (m.id)}
<li>{m.name} <button onclick={() => cart.add(m.name)}>Add</button></li>
{/each}
</ul>
One whole page: the shopping list
The project's new page is Mrs. Sri's shopping list for the market. It uses nearly everything from the Svelte track in one component:
<!-- src/routes/shopping/+page.svelte -->
<script>
let shopping = $state([])
let input = $state("")
let nextId = 1
let remaining = $derived(shopping.filter((b) => !b.bought).length)
function add() {
if (!input.trim()) return
shopping.push({ id: nextId++, name: input, bought: false })
input = ""
}
function remove(id) {
shopping = shopping.filter((b) => b.id !== id)
}
</script>
<h2>Market Shopping</h2>
<p>{remaining} not bought yet of {shopping.length}</p>
<form onsubmit={(e) => { e.preventDefault(); add() }}>
<input bind:value={input} placeholder="What to buy?" />
<button>Add</button>
</form>
<ul>
{#each shopping as b (b.id)}
<li>
<input type="checkbox" bind:checked={b.bought} />
<span class:bought={b.bought}>{b.name}</span>
<button onclick={() => remove(b.id)}>Remove</button>
</li>
{/each}
</ul>
<style>
.bought { text-decoration: line-through; opacity: 0.5; }
</style>
shoppingandinputchange while the page is in use, so both are$state.nextIdis just a counter that never shows on screen, so a plainletis enough.let remaining = $derived(...length)is a derived value: recomputed every timeshoppingchanges, ticking an item included.onsubmit={(e) => { e.preventDefault(); add() }}stops the browser from sending the form itself, then runsadd. Withoute.preventDefault(), a plain Svelte page (like the exercise editor) reloads and the list is gone. SvelteKit catches GET forms as navigation in the browser, so in this project the list happens to survive; still writee.preventDefault(), because this form isn't meant to change pages.bind:value={input}binds the field both ways: typing fillsinput, andinput = ""empties the field.if (!input.trim()) returnturns away an empty field, so there's no empty row in the list.{#each shopping as b (b.id)}draws one<li>per item, withb.idas the key.shopping.push(...)adds the item straight into the$statearray, and the screen follows.bind:checked={b.bought}andclass:boughtstrike through items already bought.bis part of the$statearray, so ticking it updatesremainingtoo.removemakes a new array without that item throughfilter, then stores it back intoshopping.
Tried with the Svelte 5.16 compiler:
| Step | shopping |
Screen |
|---|---|---|
| start | [] |
0 not bought yet of 0, an empty list |
| type "Rice", Add | 1 item | 1 not bought yet of 1, the field empty again |
| type "Eggs", Add | 2 items | 2 not bought yet of 2 |
| tick Rice | Rice bought: true |
1 not bought yet of 2, Rice struck through |
| Add with an empty field | still 2 | no new row |
| Remove Eggs | 1 item | 0 not bought yet of 1 |
Why push just works
shopping is made with $state([]), so Svelte watches its contents, not just the variable. shopping.push(item) updates the list and remaining right away, and so does ticking b.bought. To remove, filter makes a new array, then shopping = shopping.filter(...) stores it. Both ways work on $state.
Without $state, let shopping = [] is a plain array. Rice goes into memory, but the screen stays at 0 not bought yet of 0, and the compiler warns non_reactive_update. In older Svelte 4 code you'll see shopping = [...shopping, item] everywhere, because there push doesn't update the screen. The last lesson covers reading code like that.
What lives in the page, and what lives in a store
shopping lives inside the page component. Move from /shopping to /menu and SvelteKit removes that component, and its contents go with it; come back to /shopping and the list is empty again. The cart isn't lost, because the cart store lives in the module src/lib/cart.js, not in the page, and the layout stays mounted. The rule: data only one page uses is fine as $state in that page; data another page or the layout reads moves into a store, or into a $state object exported from a .svelte.js file.
Exercises: Todo App and Shopping List
Both exercises are a list like the one above, as a standalone app, so their heading is an <h1>.
- Todo App: the starter already has
todosandinput(both$state),let remaining = $derived(...), anaddTodo()that usestodos.push(...),removeTodo(),<h1>Todo App</h1>, and<p>{remaining} left</p>. You add<form onsubmit={(e) => { e.preventDefault(); addTodo() }}>holding<input bind:value={input} />and<button type="submit">Add</button>, then a<ul>with{#each todos as todo (todo.id)}, abind:checked={todo.done}checkbox, and a Remove button withonclick. The checker typesLearn Svelte, presses Add, and looks for that text in the<ul>. - Shopping List: the starter has
itemsandinput(both$state),<h1>Shopping List</h1>, and<p>Total items: {items.length}</p>. You writeaddItem()andremoveItem(id)yourself, just likeaddandremoveabove, then the form and its<ul>. The checker typesCoffee.
In both, the button reads exactly Add, the field is empty again after an item goes in, and Add with an empty field makes no <li>.
⚠️ Why the list sits still or disappears
- An array without
$state:pushgrows the data in memory, but the screen stays still. Writelet items = $state([]). - Without
e.preventDefault()inonsubmit, the browser sends the form too. In the exercise editor, the page reloads and the list is gone. - After an item goes in, empty the field with
input = ""; the checker looks for an empty field. - Without
if (!input.trim()) return, Add with an empty field makes an empty<li>, and the checker rejects it. - Shared data kept in a page's
$stateis gone as soon as you change pages. Move it into a store when another page or the layout reads it.
TL;DR: A Svelte project brings all the lessons together: routes and a +layout.svelte with {@render children()}, load for data (let { data } = $props()), a store in src/lib for data many pages use (the cart in the header), a form action for orders, and page components. One list page uses let shopping = $state([]), bind:value={input}, <form onsubmit={(e) => { e.preventDefault(); add() }}>, {#each shopping as b (b.id)}, bind:checked, class:, and let remaining = $derived(shopping.filter((b) => !b.bought).length). Because shopping is $state, adding is just shopping.push(item), and removing shopping = shopping.filter(...). Turn away an empty field with if (!input.trim()) return and empty it with input = "". A page's state is lost when you change pages; a store stays. The exercises: a Todo App with the words Learn Svelte and a Shopping List with Coffee, their button Add.
⚡ One page, many lessons
Write:
<script>
let shopping = $state([])
let input = $state("")
let nextId = 1
let remaining = $derived(shopping.filter((b) => !b.bought).length)
function add() {
if (!input.trim()) return
shopping.push({ id: nextId++, name: input, bought: false })
input = ""
}
</script>
Meaning: shopping and input change while the page is in use, so both are $state. remaining is a derived value, recomputed every time shopping changes. if (!input.trim()) return turns away an empty field, and input = "" empties it again.
⚡ A form that doesn't reload
Write:
<form onsubmit={(e) => { e.preventDefault(); add() }}>
<input bind:value={input} placeholder="What to buy?" />
<button>Add</button>
</form>
Guess first: e.preventDefault() is deleted, then Add is pressed in the exercise editor. What happens to the list?
It's gone. The browser sends the form too, a plain Svelte page reloads, and all state starts empty again.
Meaning: bind:value={input} binds the field both ways: typing fills input, and input = "" empties the field.
⚡ State in the page, a store for sharing
Guess first: you move from /shopping to /menu, then come back. Is the shopping list still there?
No, it's empty again. shopping lives inside the page component, and SvelteKit removes that component when you change pages. The cart survives because the cart store lives in the module src/lib/cart.js.
Meaning: Data only one page uses is fine as $state in that page. Data another page or the layout reads moves into a store.