0
0
Svelteframework~30 mins

Derived stores in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Derived Stores in Svelte
📖 Scenario: You are building a simple Svelte app that tracks the number of items in a shopping cart and calculates the total price automatically.
🎯 Goal: Create a Svelte app that uses a writable store for the cart items and a derived store to calculate the total price. The total price updates automatically when the cart changes.
📋 What You'll Learn
Create a writable store called cart with initial items and prices
Create a derived store called totalPrice that calculates the sum of item prices in cart
Use the cart and totalPrice stores in a Svelte component to display the items and total
Update the total price automatically when cart changes
💡 Why This Matters
🌍 Real World
Derived stores help keep related data in sync automatically, like calculating totals or filtered lists in shopping carts or dashboards.
💼 Career
Understanding derived stores is key for building reactive, maintainable Svelte apps that update UI automatically when data changes.
Progress0 / 4 steps
1
Create the initial cart store
Create a writable store called cart with these exact items: an array of objects with { id: 1, name: 'Apple', price: 1.5 } and { id: 2, name: 'Banana', price: 0.9 }.
Svelte
Hint

Use writable from svelte/store and assign the array with the two objects to cart.

2
Create a derived store for total price
Import derived from svelte/store and create a derived store called totalPrice that depends on cart and calculates the sum of all price values in cart.
Svelte
Hint

Use derived(cart, $cart => ...) and inside use reduce to sum prices.

3
Display cart items and totalPrice in a Svelte component
In a Svelte component, import cart and totalPrice stores. Use {$cart} to loop over items and show each name and price. Below, show the total price using {$totalPrice}.
Svelte
Hint

Use {#each $cart as item} to loop and {$totalPrice} to show total.

4
Add a button to add a new item and update total automatically
Add a button that, when clicked, adds a new item { id: 3, name: 'Orange', price: 1.2 } to the cart store using its update method. The totalPrice should update automatically.
Svelte
Hint

Use cart.update to add the new item inside the addOrange function and bind it to the button's on:click.