Reading Tasks
In this section, we'll create the structure for our tasks and render them to the screen.
Also, run the dev server and open the respective dev URL as shown by Vite in your browser.
Data Structure
Let's think about the data structure for our tasks. We'll need to think about the following:
- What properties does a task have?
- What types do those properties have?
- What is the shape of the data?
Let's start with the first question. What properties does a task have? We'll start with the following:
- Unique ID
- Title
- Completion Status
- Priority (optional)
Now let's think about the types for each of these properties. We'll start with the following:
- Unique ID can be a number or a string, but we'll use a number for now.
- Title is a string.
- Completion Status is a boolean.
- Priority is optional, but it can only be one of three values:
'p1'
,'p2'
, or'p3'
.
This gives us the following types for Task
and Priority
:
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.
Render Tasks with Default Data
Now that we have our Task
data structure type, let's create some default data to work with. We'll create an array of tasks
, and we'll use the Task
data structure we just created to define the types for the array.
Now that we have some data, let's render it to the screen. How do we do that in Svelte?
The (task.id)
expression is required when rendering a list of items. It
helps Svelte keep track of which items have changed, are added, or are
removed.
But where do we add this entire code? In SvelteKit, we have a src/routes/+page.svelte
file which indicates the root URL of our app.
Putting it all together, we should have the following +page.svelte
file:
The <script>
opening and </script>
closing tags encapsulate all the JavaScript code. By setting the lang="ts"
attribute, we indicate that we're using TypeScript.
In Svelte, we can only have one component in a file. We can't have multiple components in the same file, in this, our div
holds the h1
and ul
elements. We'll break this file in the subsequent sections.
Great! We've created some default data and rendered it to the screen. In the next section, we'll add some interactivity by creating an input and button to add new tasks.
At this point, your code should be a good match to the branch of the repository: 2-reading-tasks