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
/**
* This chat application allows users to post messages and view a log of all messages.
* It uses SQLite for persistence and React for the frontend.
* The server handles message posting and retrieval, while the client renders the UI.
*/
/** @jsxImportSource https://esm.sh/react */
import React, { useState, useEffect } from "https://esm.sh/react";
import { createRoot } from "https://esm.sh/react-dom/client";
interface Message {
id: number;
content: string;
timestamp: string;
}
function App() {
const [messages, setMessages] = useState<Message[]>([]);
const [newMessage, setNewMessage] = useState("");
useEffect(() => {
fetchMessages();
}, []);
const fetchMessages = async () => {
const response = await fetch("/messages");
const data = await response.json();
setMessages(data);
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!newMessage.trim()) return;
await fetch("/messages", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ content: newMessage }),
});
setNewMessage("");
fetchMessages();
};
return (
<div className="container">
<h1>Chat Log</h1>
<form onSubmit={handleSubmit}>
<input
type="text"
value={newMessage}
onChange={(e) => setNewMessage(e.target.value)}
placeholder="Type a message..."
/>
<button type="submit">Send</button>
</form>
<div className="message-log">
{messages.map((message) => (
<div key={message.id} className="message">
<span className="timestamp">{new Date(message.timestamp).toLocaleString()}</span>
<p>{message.content}</p>
</div>
))}
</div>
<a href={import.meta.url.replace("esm.town", "val.town")} target="_blank" rel="noopener noreferrer" className="view-source">View Source</a>
<pre className="api-examples">
{`// Axios example
const axios = require('axios');
// POST a new message
axios.post('/messages', {
content: 'Hello, World!'
})
.then(response => console.log(response.data))
.catch(error => console.error(error));
// GET all messages
axios.get('/messages')
.then(response => console.log(response.data))
.catch(error => console.error(error));
// cURL examples
# POST a new message
curl -X POST /messages \\
-H "Content-Type: application/json" \\
-d '{"content":"Hello, World!"}'
# GET all messages
curl /messages`}
</pre>
</div>
);
}
function client() {
createRoot(document.getElementById("root")!).render(<App />);
}
if (typeof document !== "undefined") {
client();
}