const API_BASE = '/api/tasks';
const taskInput = document.getElementById('taskInput');
const addBtn = document.getElementById('addBtn');
const taskList = document.getElementById('taskList');
async function fetchTasks() {
try {
const response = await fetch(API_BASE);
const tasks = await response.json();
renderTasks(tasks);
} catch (error) {
console.error('Error fetching tasks:', error);
}
}
function renderTasks(tasks) {
taskList.innerHTML = '';
if (tasks.length === 0) {
taskList.innerHTML = '
No tasks yet. Add one above!
';
return;
}
tasks.forEach(task => {
const li = document.createElement('li');
li.className = `task-item ${task.completed ? 'completed' : ''}`;
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.checked = task.completed;
checkbox.addEventListener('change', () => toggleTask(task));
const span = document.createElement('span');
span.textContent = task.name;
const deleteBtn = document.createElement('button');
deleteBtn.className = 'delete-btn';
deleteBtn.textContent = 'Delete';
deleteBtn.addEventListener('click', () => deleteTask(task.id));
li.appendChild(checkbox);
li.appendChild(span);
li.appendChild(deleteBtn);
taskList.appendChild(li);
});
}
async function addTask() {
const name = taskInput.value.trim();
if (!name) return;
try {
const response = await fetch(API_BASE, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name, completed: false }),
});
if (response.ok) {
taskInput.value = '';
await fetchTasks();
}
} catch (error) {
console.error('Error adding task:', error);
}
}
async function toggleTask(task) {
try {
const response = await fetch(`${API_BASE}/${task.id}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: task.name,
completed: !task.completed
}),
});
if (response.ok) {
await fetchTasks();
}
} catch (error) {
console.error('Error toggling task:', error);
}
}
async function deleteTask(id) {
try {
const response = await fetch(`${API_BASE}/${id}`, {
method: 'DELETE',
});
if (response.ok || response.status === 204) {
await fetchTasks();
}
} catch (error) {
console.error('Error deleting task:', error);
}
}
addBtn.addEventListener('click', addTask);
taskInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
addTask();
}
});
fetchTasks();