Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Readme

A simple TODO list using Blob Storage

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
/** @jsxImportSource https://esm.sh/react */
import React, { useEffect, useState } from "https://esm.sh/react";
import { createRoot } from "https://esm.sh/react-dom/client";
function App() {
const [todos, setTodos] = useState([]);
const [newTodo, setNewTodo] = useState("");
useEffect(() => {
fetchTodos();
}, []);
const fetchTodos = async () => {
const response = await fetch("/todos");
const data = await response.json();
setTodos(data);
};
const addTodo = async (e) => {
e.preventDefault();
if (!newTodo.trim()) return;
await fetch("/todos", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ text: newTodo }),
});
setNewTodo("");
fetchTodos();
};
const deleteTodo = async (id) => {
await fetch(`/todos/${id}`, { method: "DELETE" });
fetchTodos();
};
return (
<div className="container">
<header>
<h1>My Todo List</h1>
</header>
<main>
<form onSubmit={addTodo} className="todo-form">
<input
type="text"
value={newTodo}
onChange={(e) => setNewTodo(e.target.value)}
placeholder="Add a new task..."
className="todo-input"
/>
<button type="submit" className="add-button">Add Task</button>
</form>
<ul className="todo-list">
{todos.map((todo) => (
<li key={todo.id} className="todo-item">
<span>{todo.text}</span>
<button
onClick={() => deleteTodo(todo.id)}
className="delete-button"
>
</button>
</li>
))}
</ul>
</main>
<footer>
<p>
<a href={import.meta.url.replace("esm.town", "val.town")}>View Source</a>
</p>
</footer>
</div>
);
}
function client() {
createRoot(document.getElementById("root")).render(<App />);
}
if (typeof document !== "undefined") {
client();
}
async function server(request: Request): Promise<Response> {
const { blob } = await import("https://esm.town/v/std/blob");
const url = new URL(request.url);
if (url.pathname === "/todos" && request.method === "GET") {
const todos = await blob.getJSON("todos") || [];
return new Response(JSON.stringify(todos), {
headers: { "Content-Type": "application/json" },
});
}
if (url.pathname === "/todos" && request.method === "POST") {
const todos = await blob.getJSON("todos") || [];
const newTodo = await request.json();
const updatedTodos = [...todos, { id: Date.now(), ...newTodo }];
await blob.setJSON("todos", updatedTodos);
return new Response(JSON.stringify(updatedTodos), {
headers: { "Content-Type": "application/json" },
muhammad_owais_warsi-todolistusingblob.web.val.run
September 2, 2024