-
Notifications
You must be signed in to change notification settings - Fork 0
/
indexed-db.html
100 lines (88 loc) · 2.96 KB
/
indexed-db.html
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>TODO with IndexeDB</title>
</head>
<body>
<h1>TODO with IndexeDB</h1>
<form id="todo-form">
<input type="text" id="todo-input" />
<button type="submit">Add</button>
</form>
<ul id="todo-list"></ul>
</body>
<script>
const todoForm = document.getElementById("todo-form");
const todoInput = document.getElementById("todo-input");
const todoList = document.getElementById("todo-list");
const DB_NAME = "todo";
const DB_VERSION = 1;
const DB_STORE_NAME = "todo";
let db;
const foo = Float32Array.from([1, 2, 3, 4, 5]);
const openDbRequest = indexedDB.open(DB_NAME, DB_VERSION);
openDbRequest.addEventListener("upgradeneeded", (event) => {
const db = event.target.result;
db.createObjectStore(DB_STORE_NAME, {
keyPath: "id",
autoIncrement: true,
});
});
openDbRequest.addEventListener("success", (event) => {
db = event.target.result;
console.log("DB opened");
readAllTodos();
addTodoToDb({ text: "test", data: foo });
});
openDbRequest.addEventListener("error", (event) => {
console.error("DB error:", event.target.error);
});
todoForm.addEventListener("submit", (event) => {
event.preventDefault();
const todo = {
text: todoInput.value,
done: false,
};
addTodoToDb(todo);
});
function addTodoToDb(todo) {
console.time("addTodoToDb");
const transaction = db.transaction(DB_STORE_NAME, "readwrite");
const store = transaction.objectStore(DB_STORE_NAME);
const request = store.add(todo);
request.addEventListener("success", (event) => {
console.log("Todo added to DB");
console.timeEnd("addTodoToDb");
readAllTodos();
});
request.addEventListener("error", (event) => {
console.error("DB error:", event.target.error);
});
}
function readAllTodos() {
console.time("readAllTodos");
const transaction = db.transaction(DB_STORE_NAME, "readonly");
const store = transaction.objectStore(DB_STORE_NAME);
const request = store.getAll();
request.addEventListener("success", (event) => {
console.log("Todos read from DB");
const todos = event.target.result;
renderTodos(todos);
});
request.addEventListener("error", (event) => {
console.error("DB error:", event.target.error);
});
console.timeEnd("readAllTodos");
}
function renderTodos(todos) {
todoList.innerHTML = "";
todos.forEach((todo) => {
const todoItem = document.createElement("li");
todoItem.textContent = todo.text;
todoList.appendChild(todoItem);
});
}
</script>
</html>