0
0
Svelteframework~30 mins

Array and object reactivity gotchas in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
Array and Object Reactivity Gotchas in Svelte
📖 Scenario: You are building a simple Svelte app to manage a list of tasks. You want to update the UI reactively when tasks are added or modified.
🎯 Goal: Learn how to properly update arrays and objects in Svelte so the UI updates automatically without manual refresh tricks.
📋 What You'll Learn
Create an array of task objects with exact properties
Add a helper variable to track new task input
Update the array reactively when adding a new task
Modify an object property reactively and update the UI
💡 Why This Matters
🌍 Real World
Managing lists of items like tasks, shopping lists, or messages in a web app requires reactive updates to show changes immediately.
💼 Career
Understanding Svelte's reactivity with arrays and objects is essential for building responsive user interfaces in modern web development jobs.
Progress0 / 4 steps
1
Create the initial tasks array
Create a variable called tasks that is an array with these exact objects: { id: 1, text: 'Buy milk', done: false } and { id: 2, text: 'Walk dog', done: true }
Svelte
Need a hint?

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

2
Add a new task input variable
Add a variable called newTaskText and set it to an empty string '' to hold the new task text input.
Svelte
Need a hint?

Declare let newTaskText = ''; below the tasks array.

3
Add a new task reactively
Add a function called addTask that pushes a new object with id as tasks.length + 1, text as newTaskText, and done as false into tasks. Then reassign tasks to itself to trigger reactivity. Finally, reset newTaskText to an empty string.
Svelte
Need a hint?

Remember to reassign tasks = tasks; after pushing to update the UI.

4
Toggle task done status reactively
Add a function called toggleDone that takes a parameter id. Inside, find the task in tasks with matching id and toggle its done property. Then reassign tasks to itself to trigger reactivity.
Svelte
Need a hint?

Use tasks.find() to locate the task and toggle done. Then reassign tasks to trigger UI update.