0
0
Svelteframework~15 mins

Auto-subscription with $ prefix in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
Auto-subscription with $ prefix in Svelte
📖 Scenario: You are building a simple Svelte app that shows a live count of items in a shopping cart. The count updates automatically when the cart changes.
🎯 Goal: Create a Svelte component that uses a writable store to hold the cart count. Use the $ prefix to auto-subscribe and display the count in the component.
📋 What You'll Learn
Create a writable store named cartCount with initial value 0
Create a variable increment that adds 1 to cartCount
Use the $ prefix to auto-subscribe to cartCount and display its value in the component
Add a button that calls increment when clicked
💡 Why This Matters
🌍 Real World
Stores and auto-subscription are used in Svelte apps to keep UI in sync with data without manual event handling.
💼 Career
Understanding Svelte stores and the $ prefix is essential for building reactive, maintainable user interfaces in modern web development.
Progress0 / 4 steps
1
Create the cartCount store
Import writable from 'svelte/store' and create a store called cartCount with initial value 0.
Svelte
Hint

Use const cartCount = writable(0) to create the store.

2
Create the increment function
Add a function called increment that updates cartCount by adding 1 using its update method.
Svelte
Hint

Use cartCount.update(n => n + 1) inside the increment function.

3
Use $ prefix to auto-subscribe and display count
In the Svelte component, use the $ prefix with cartCount to auto-subscribe and display the current count inside a <p> tag.
Svelte
Hint

Use {$cartCount} inside the paragraph to show the current count.

4
Add a button to increment the count
Add a <button> element with text + that calls the increment function when clicked using on:click.
Svelte
Hint

Use <button on:click={increment}>+</button> to add the button.