Adding Tasks
In this section, we'll add the ability to add tasks to the list.
Let us add interactivity by letting the user add tasks to the list. We'll add a text input and a button. When the user clicks the button, we'll add the text from the input to the list of tasks.
Adding a Text Input and Button
First, add a text input and a button to the page. We'll add them just above the list of tasks.
Though this is good enough for now, we can and should make it more accessible by adding a label for the input and a for
attribute on the label that matches the id
of the input.
Now, clicking on the label will focus on the input.
Adding a Task
The Add button doesn't do anything yet. Let's add a click handler to it that will log to the console for now.
Let's capture the value of the input and log it to the console. One of the ways to do this in Svelte is to bind a variable to track the value of the input.
All we need to do is add a bind:value
attribute to the input and track it in the taskName
variable.
Now, we can update the button click handler to log the value of the input.
Before we can even add tasks to the list, we have to update our current tasks
variable that holds our list of tasks to be mutable a.k.a a let
; otherwise, the list will not update when we add a task.
We can add a task to the list by updating the tasks
state variable. We can push the new task onto the end of the array but to re-render the list we must reassign the tasks array to itself. This is how reactivity in Svelte works, through assignments. This would have been natural if it was a primitive data type like a string or number. This is not the case with Objects and Arrays.
If that felt weird, there is a more meaningful way to add tasks to the list.
As discussed in the previous section, unique IDs are usually created by a database. In this project, we'll use the current time in milliseconds as the ID for each task.
Type in the input and hit the Add
button, we should be able to add tasks to the list!
Our Svelte file is getting a bit long and messy, so let's separate the button's on:click
handler into its function.
This is how your final Svelte code should look.
Awesome, but there are a ton of things that can go wrong when a user adds a task. For example, the user can add an empty task.
This gives us a good opportunity to learn about Testing. We'll cover testing in the subsequent sections.
At this point, your code should be a good match to the branch of the repository: 3-adding-tasks