Add item, update state (ok)
C:\Users\Administrator\Desktop\test\src\index.ts
import { v4 as uuidV4 } from "uuid";
type Task = {
id: string,
title: string,
completed: boolean,
createdAt: Date
}
const tasks: Task[] = getListItem();
const list = document.querySelector<HTMLUListElement>("#list");
const form = document.querySelector<HTMLFormElement>("#new-task-form");
const input = document.querySelector<HTMLInputElement>("#new-task-title");
tasks.forEach(addListItem);
form?.addEventListener("submit", (e) => {
e.preventDefault();
if (!input?.value) return;
const newTask: Task = {
id: uuidV4(),
title: input.value,
completed: false,
createdAt: new Date()
}
tasks.push(newTask);
addListItem(newTask);
input.value = "";
});
function addListItem(task: Task) {
const item = document.createElement("li")
const label = document.createElement('label')
const checkbox = document.createElement('input')
checkbox.addEventListener("change", () => {
task.completed = checkbox.checked;
saveTasks();
})
checkbox.type = "checkbox"
checkbox.checked = task.completed
// compine all the field/ elements into one using the array append method
label.append(checkbox, task.title)
item.append(label)
list?.append(item);
console.log(task.title);
}
function getListItem(): Task[] {
const taskJson = localStorage.getItem('TASKS');
if (!taskJson) return [];
return JSON.parse(taskJson);
}
const saveTasks = () => {
localStorage.setItem("TASKS", JSON.stringify(tasks))
}
Last updated