0
0
Svelteframework~30 mins

Readable stores in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Readable Stores in Svelte
📖 Scenario: You are building a simple Svelte app that shows the current time updating every second. You want to use a readable store to hold the time so that your components can reactively display it.
🎯 Goal: Create a readable store that updates the current time every second and use it in a Svelte component to display the live time.
📋 What You'll Learn
Create a readable store called time that holds the current time as a string.
Set up the store to update every second with the new current time.
Use the time store in a Svelte component to display the live time.
Ensure the store cleans up the timer when no components are subscribed.
💡 Why This Matters
🌍 Real World
Live clocks and timers are common in dashboards, apps, and websites. Using readable stores helps keep the UI reactive and efficient.
💼 Career
Understanding Svelte stores and accessibility is important for frontend developers building interactive and inclusive web applications.
Progress0 / 4 steps
1
Create the time readable store with initial value
Import readable from 'svelte/store' and create a readable store called time with the initial value set to the current time string using new Date().toLocaleTimeString().
Svelte
Hint

Use readable(initialValue, startFunction) to create the store. The initial value is the current time string.

2
Add a timer to update the time store every second
Inside the readable store's start function, set up a setInterval that updates the store's value every 1000 milliseconds with the current time string using set(new Date().toLocaleTimeString()). Also, return a cleanup function that clears the interval.
Svelte
Hint

Use setInterval to update the store every second and clear it on cleanup.

3
Create a Svelte component that uses the time store
In a Svelte component, import the time store and use the $time syntax to display the current time inside a <main> element with a heading <h1> that says "Current Time:" followed by the live time.
Svelte
Hint

Use $time to access the store's current value reactively in the template.

4
Add accessibility and semantic HTML to the component
Ensure the <main> element has an aria-label attribute with the value "Live clock" for accessibility. Also, add a <section> inside <main> wrapping the <h1> with a role="region" and aria-live="polite" to announce time updates to screen readers.
Svelte
Hint

Use aria-label on main and aria-live="polite" on a section to improve screen reader announcements.