Save, Get localStorage (ok)

C:\Users\Administrator\Desktop\test\tsconfig.json

{
  "compilerOptions": {
    "noImplicitAny": true,
    "target": "ES5",
    "module": "ES2015"
  }
}

C:\Users\Administrator\Desktop\test\package.json

{
  "name": "webpack-setup",
  "version": "1.0.0",
  "description": "",
  "main": "src/index.ts",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack-dev-server --mode development",
    "build": "webpack --mode production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/canvas-confetti": "^1.6.3",
    "@types/uuid": "^9.0.7",
    "css-loader": "^6.7.1",
    "html-webpack-plugin": "^5.5.0",
    "mini-css-extract-plugin": "^2.6.1",
    "ts-loader": "^9.5.0",
    "webpack": "^5.89.0",
    "webpack-cli": "^5.1.4",
    "webpack-dev-server": "^4.15.1"
  },
  "dependencies": {
    "canvas-confetti": "^1.9.0",
    "typescript": "^5.2.2",
    "uuid": "^9.0.1"
  }
}

C:\Users\Administrator\Desktop\test\src\index.ts

import { v4 as uuidV4 } from "uuid";
type Task = {
  id: string,
  title: string,
  completed: false,
  createdAt: Date
}
const list = document.querySelector<HTMLUListElement>("#list");
const form = document.querySelector<HTMLFormElement>("#new-task-form");
const input = document.querySelector<HTMLInputElement>("#new-task-title");
const tasks: Task[] = getListItem();
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(tasks);
  input.value = "";
});
function addListItem(tasks: Task[]): void {
  localStorage.setItem('TASKS', JSON.stringify(tasks));
}
function getListItem(): Task[] {
  const taskJson = localStorage.getItem('TASKS');
  if (!taskJson) return [];
  return JSON.parse(taskJson);
}

C:\Users\Administrator\Desktop\test\src\custom.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <style>
    #list{
      list-style: none;
      padding: 0;
    }
  </style>
</head>
<body>
  <div class="cal">
    <center>
      <li id="list"></li>
      <form id="new-task-form">
        <input type="text" id="new-task-title">
        <button type="submit">Add</button>
      </form>
    </center>
  </div>
</body>
</html>

Last updated