We want to fetch and display tasks that are stored in the database. Hereโs what youโll get by the end of this lesson:
The first step is to create a user for the Todolist API.
Creating a user
This creates an โaccountโ for your tasks. To create a user, you send a POST request to /users.
<body> <!-- ... -->
<!-- zlFetch Library --> <script src="https://cdn.jsdelivr.net/npm/zl-fetch"></script></body>const rootendpoint = 'https://api.learnjavascript.today'
zlFetch .post(`${rootendpoint}/users`, { body: { username: 'your-username', password: 'your-password', }, }) .then(response => console.log(response.body)) .catch(error => console.log(error))You should get a response that the user is created.
Note: You only need to create a user once. You can delete this code once youโve created your user.
Fetching tasks
The Todolist API creates three tasks for you automatically. I made it this way because I want you to learn to fetch tasks first. (Itโs easier to learn this way).
To fetch tasks, you need to send a GET request to /tasks. Make sure you include your username and password to authenticate yourself.
zlFetch(`${rootendpoint}/tasks`, { auth: { username: 'your-username', password: 'your-password', },}) .then(response => console.log(response.body)) .catch(error => console.error(error))You should see three tasks in your console. The three default tasks are:
- Learn JavaScript for 30 minutes
- Build a todolist
- Drink water
We need to use username and password to authenticate ourselves for every request we make to the Todolist API. To make this easier, we can create an auth variable at the start. And we can reuse this auth variable when we need it.
const auth = { username: 'your-username', password: 'your-password',}Hereโs how we can use the auth variable:
zlFetch(`${rootendpoint}/tasks`, { auth }) .then(response => console.log(response.body)) .catch(error => console.log(error))Adding tasks to the DOM
To add tasks to the DOM, we have to:
- Loop through the fetched tasks
- For each task, make a task element
- Append the task element to the DOM
First, letโs loop through the fetched tasks.
zlFetch(/*...*/).then(response => { const tasks = response.body tasks.forEach(task => { // Create Task element // Append task element to DOM })})Each task has three properties. You can see it if you console.log it.
id: ID of the taskdone: Whether the task is completedname: Name of the task
We can make the task with the name property.
zlFetch(/*...*/).then(response => { const tasks = response.body tasks.forEach(task => { const taskElement = makeTaskElement(task.name) })})Once the task is made, we can append it to the DOM.
zlFetch(/*...*/).then(response => { // ... tasks.forEach(task => { const taskElement = makeTaskElement(task.name) taskList.appendChild(taskElement) })})Tasks are now added to the DOM.
You see the empty state because it takes time to fetch tasks from the Todolist API. Weโll fix empty state issue in a bit.
Changing the id
Each task from the database contains an id. If we use this id, we donโt need to generate one ourselves. Letโs change makeTaskElement to take in this id.
While weโre at it, letโs also accept the done property. (Weโll use it when we edit tasks in a later lesson).
function makeTaskElement({ id, name, done }) { const taskElement = document.createElement('li') taskElement.classList.add('task') taskElement.innerHTML = DOMPurify.sanitize(` <input type="checkbox" id="${id}" /> <label for="${id}"> ... </label> <span class="task__name">${name}</span> <button type="button" class="task__delete-button"> <svg viewBox="0 0 20 20"> ... </svg> </button> `) return taskElement}With this change, we can create a task element like this:
zlFetch(/*...*/).then(response => { // ... tasks.forEach(task => { const taskElement = makeTaskElement(task) // ... })})Since we changed makeTaskElement, we need to update parts of the code we used it in.
// Adding a task to the DOMtodolist.addEventListener('submit', event => { // ... const id = generateUniqueString(10) const taskElement = makeTaskElement({ id, name: inputValue, done: false, }) // ...})Fixing the empty-state flash
Right now, the Todolist flashes an empty state for a bit before populating the DOM with tasks. This can create confusion for users if they knew theyโve created some tasks.
We want to find a way to tell users weโre fetching their tasks from the database. The simplest way is to change empty state message.
<div class="todolist__empty-state"> Fetching your tasks... Please wait a bit... โฐ.</div>After tasks are fetched, we change the message of the empty state again.
const emptyStateDiv = todolist.querySelector('.todolist__empty-state')
zlFetch(/*...*/) .then(response => { // Append tasks to DOM...
// Change empty state text emptyStateDiv.textContent = 'Your todo list is empty. Hurray! ๐' }) .catch(error => console.log(error))
Thatโs it!
Welcome! Unfortunately, you donโt have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson