Skip to content
Snippets Groups Projects

Adding toDo app functionability

Merged Jesus Galaz Reyes requested to merge 2-build-javascript-core-functionality into main
All threads resolved!
Files
2
+ 38
2
// Obtener referencia a los elementos del DOM
// Get reference to DOM elements
const taskList = document.querySelector('.task-list ul');
const newTaskForm = document.querySelector('form');
@@ -16,6 +16,24 @@ document.getElementById('logout-btn').addEventListener('click', async () => {
}
});
// Function to check if the currently processed task belongs to user account
async function isValidTask(taskId) {
try {
const res = await fetch("/api/todos");
const todos = await res.json();
let valid = false;
todos.forEach(todo => {
if (todo._id == taskId)
valid = true;
});
return valid;
} catch (err) {
console.error("Error loading tasks:", err);
}
}
// Load every task when the page is initialzed
document.addEventListener('DOMContentLoaded', async () => {
try {
@@ -78,7 +96,7 @@ newTaskForm.addEventListener('submit', async (e) => {
const newTodo = await res.json();
taskList.appendChild(createTaskElement(newTodo));
input.value = ''; // Limpiar el campo de entrada
input.value = ''; // Clear input field
} catch (err) {
console.error('Error adding task:', err);
}
@@ -86,6 +104,12 @@ newTaskForm.addEventListener('submit', async (e) => {
// Mark task as completed
async function markAsDone(taskId, isDone) {
// Input sanitation
if (isNaN(parseInt(taskId, 10)) && typeof(isDone) === 'boolean' && isValidTask(taskId)) {
console.error('Invalid task ID, task status is invalid or task does not belong to account');
return;
}
try {
const res = await fetch(`/api/todos/${taskId}/done`, {
method: 'PUT',
@@ -104,6 +128,12 @@ async function markAsDone(taskId, isDone) {
// Erase task
async function deleteTask(taskId) {
// Input sanitation
if (isNaN(parseInt(taskId, 10))) {
console.error('Invalid task ID');
return;
}
try {
const res = await fetch(`/api/todos/${taskId}`, {
method: 'DELETE'
@@ -122,6 +152,12 @@ async function deleteTask(taskId) {
// Edit task
async function updateTask(taskId, newDescription) {
// Input sanitation
if (isNaN(parseInt(taskId, 10)) && typeof(newDescription) === 'string' && isValidTask(taskId)) {
console.error('Invalid task ID, task status is invalid or task does not belong to account');
return;
}
try {
const res = await fetch(`/api/todos/${taskId}/description`, {
method: 'PUT',
Loading