π Introduction: Deleting a To-Do
In this lesson, we will add delete functionality to our to-do app.
This will allow users to remove tasks permanently from their list.
By the end of this tutorial, users will be able to delete any task directly from the edit page.
ποΈ Step 1: Add a Delete Button in the Edit To-Do Page
Open
edit-todo.htmlin thetemplatesfolder.Scroll to the bottom of the form where the "Edit To-Do" button and "Back" anchor tag are located.
Add a new delete button between them:
<button id="delete-button" type="button" class="btn btn-danger">
ποΈ Delete
</button>ID:
delete-buttonβ used by JavaScript to attach functionality.Class:
btn btn-dangerβ gives it a red color to indicate deletion.Text: Delete with a trash icon ποΈ for clarity.
Save the file.
π Step 2: Implement Delete in JavaScript
Open
base.jsin yourstatic/js/folder.Locate the edit to-do section of the code.
Add a function to handle the delete button:
const deleteBtn = document.getElementById('delete-button');
if (deleteBtn) {
deleteBtn.addEventListener('click', async () => {
const todoId = /* fetch the current todo's ID, passed from template */;
const token = document.cookie
.split('; ')
.find(row => row.startsWith('access_token='))
.split('=')[1];
const response = await fetch(`/todos/delete/${todoId}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${token}`
}
});
if (response.ok) {
window.location.href = '/todos/todo-page';
} else {
alert('Failed to delete to-do.');
}
});
}Access Token: ensures only authorized users can delete tasks.
Redirect: after deletion, user is sent back to the home page.
Error Handling: shows an alert if deletion fails.
π Step 3: Test the Delete Functionality
Run your FastAPI application:
uvicorn app.main:app --reloadOpen your browser and sign in.
Navigate to the Edit To-Do page of any task.
Click the Delete ποΈ button.
Verify:
The task is removed from the list.
You are redirected back to the to-do home page.
β Step 4: Summary
Added a Delete button to the Edit To-Do page ποΈ.
Implemented JavaScript functionality to call the DELETE endpoint in FastAPI.
Users can now safely remove tasks, keeping their to-do list up-to-date.
The application now fully supports:
Creating To-Dos β
Editing To-Dos βοΈ
Deleting To-Dos ποΈ
Marking as complete β
Authentication & logout π
With this, your full-stack To-Do app is complete and functional.