0
0
Svelteframework~30 mins

Immutable patterns for updates in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
Immutable patterns for updates in Svelte
📖 Scenario: You are building a simple Svelte app to manage a list of tasks. Each task has a name and a completion status. You want to update the tasks immutably to keep your app predictable and avoid bugs.
🎯 Goal: Create a Svelte component that holds a list of tasks as an array of objects. Then, add a way to toggle the completion status of a task using immutable update patterns.
📋 What You'll Learn
Create a tasks array with three tasks, each with id, name, and completed properties
Create a variable taskToToggle to hold the id of the task to update
Use an immutable update pattern to create a new array with the toggled task's completed value
Add a button in the markup to toggle the completion status of the first task immutably
💡 Why This Matters
🌍 Real World
Immutable updates help avoid bugs and make state changes predictable in UI frameworks like Svelte. This pattern is common in apps managing lists or collections of data.
💼 Career
Understanding immutable update patterns is essential for frontend developers working with reactive frameworks to write clean, bug-free, and maintainable code.
Progress0 / 4 steps
1
Create the initial tasks array
Create a variable called tasks and set it to an array with these three objects exactly: { id: 1, name: 'Wash dishes', completed: false }, { id: 2, name: 'Do laundry', completed: false }, and { id: 3, name: 'Take out trash', completed: false }.
Svelte
Need a hint?

Use let tasks = [ ... ] with the exact objects inside the array.

2
Add a variable for the task to toggle
Create a variable called taskToToggle and set it to the number 1 to represent the id of the task you want to update.
Svelte
Need a hint?

Use let taskToToggle = 1; to store the id of the task to update.

3
Create an immutable update for toggling task completion
Create a new variable called updatedTasks that uses tasks.map() to return a new array. Inside the map, if the task's id matches taskToToggle, return a new object with the same id and name but with completed set to the opposite of its current value. Otherwise, return the task unchanged.
Svelte
Need a hint?

Use tasks.map() and inside the callback, check if task.id === taskToToggle. If yes, return a new object with spread syntax and toggled completed. Otherwise, return the original task.

4
Add a button to toggle the first task's completion immutably
Add a <button> element below the script that, when clicked, sets tasks to updatedTasks. The button text should be Toggle First Task. This completes the immutable update pattern in the Svelte component.
Svelte
Need a hint?

Add a button with on:click event that sets tasks = updatedTasks. Use accessible aria-label for clarity.