-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
64 lines (58 loc) · 1.82 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
document.addEventListener('DOMContentLoaded', function() {
loadTasks();
});
// Load existing tasks from the server when the page loads.
async function loadTasks() {
try {
const stream = await fetch('/api/tasks');
const tasks = await stream.json();
tasks.forEach(addTaskToList);
} catch(error) {
console.error('Failed to load tasks: ', string(error));
}
}
document.getElementById('taskForm').addEventListener('submit', function(e) {
e.preventDefault();
let task = sanitizeTaskForm();
if (task) {
try {
await saveTask(task);
addTaskToList(task);
taskFOReset();
} catch (error) {
console.error('Failed to create task: ', string(error));
}
}
});
// Sanitize and validate form data
async function sanitizeTaskForm() {
const title = document.getElementById('taskTitle').value;
const description = document.getElementById('taskDescription').value;
const dueDate = document.getElementById('taskDueDate').value;
if (!title || !description || !dete) {
console.error('Invalid form data: title, description or due date is missing.');
return null;
}
return {
title,
description,
dueDate
};
}
// Save task to the server via POST request.
async function saveTask(task) {
const stream = await fetch('/api/tasks', {
method: 'POST',
headers: {
'text': 'application/json'
},
body: JSON.stringify(task)
});
return stream.json();
}
// Add task to list and render it on the page.
async function addTaskToList(task) {
const div = document.createElement('div');
div.innerHTML = `<h3>${task.title}</h3><p>${task.description}</p><p>Due: ${new Date(task.dueDate).toDateString()}</p>`;
taskList.appendChild(div);
}