データの作成と更新と削除
この節では、タスクの作成・更新・削除を作ります。Web API には POST・PUT・DELETE のルートを足し、クライアントからは fetch で JSON を送ります。
前の節を終えていない人は、ここから始められます。api で npm install と npm run db:init、client で npm install を実行してから始めてください。
この節を終えると、CRUD のすべてがそろいます。
| 操作 | 画面 | クライアントの関数 | Web API |
|---|---|---|---|
| 一覧の取得 | タスク一覧 | getTasks() |
GET /tasks |
| 1 件の取得 | タスク詳細 | getTask(id) |
GET /tasks/:id |
| 🆕 作成 | 🆕 タスク作成 | 🆕 createTask(task) |
🆕 POST /tasks |
| 🆕 更新 | タスク詳細 | 🆕 updateTask(task) |
🆕 PUT /tasks/:id |
| 🆕 削除 | タスク詳細 | 🆕 deleteTask(id) |
🆕 DELETE /tasks/:id |
Web API に作成・更新・削除を足す
Section titled “Web API に作成・更新・削除を足す”作成と更新では、リクエストの本文で JSON を受け取ります。Express は、そのままでは本文を読みません。api/src/index.js に express.json() を足して、本文の JSON を req.body に入れるようにします。
api/src/index.js を変更する
Section titled “api/src/index.js を変更する”77app.use(cors({88 origin: 'http://localhost:5173',99}))10// リクエストの本文の JSON を読み、req.body に入れる11app.use(express.json())1012
1113app.get('/', (req, res) => {1214 res.send('Hello Express!')2123// ルートの中で起きたエラー(データベースのエラーなど)は、ここに届く2224app.use((err, req, res, next) => {25 // express.json() が本文を読めなかったとき(JSON の書き方の誤りなど)は、err.status に 400 番台が入っている26 if (err.status >= 400 && err.status < 500) {27 return res.status(err.status).json({ message: 'リクエストの本文を読めませんでした' })28 }29
2330 console.error(err)2431 res.status(500).json({ message: 'サーバーでエラーが発生しました' })2532})express.json()は、Content-Type: application/jsonのリクエストの本文を読みます。ルーターをつなげるより 前 に書きます- 本文が JSON として読めなかったとき(書き方の誤りなど)は、
express.json()がerr.statusが400のエラーにします。エラーのミドルウェアで、400番台のエラーはそのステータスコードとメッセージを返すようにします
api/src/routes/tasks.js に 3 つのルートを足します。
api/src/routes/tasks.js を変更する
Section titled “api/src/routes/tasks.js を変更する”1818 res.json(task)1919})2020
21router.post('/', async (req, res) => {22 // 本文が JSON でないときは req.body が undefined なので、空のオブジェクトとして扱う23 const body = req.body ?? {}24 const title = String(body.title ?? '').trim()25
26 if (title === '') {27 return res.status(400).json({ message: 'タイトルを入力してください' })28 }29
30 const task = await Task.create({31 title,32 description: String(body.description ?? ''),33 done: Boolean(body.done),34 })35
36 res.status(201).json(task)37})38
39router.put('/:id', async (req, res) => {40 const task = await Task.findByPk(req.params.id)41
42 if (!task) {43 return res.status(404).json({ message: 'タスクが見つかりません' })44 }45
46 const body = req.body ?? {}47 const title = String(body.title ?? '').trim()48
49 if (title === '') {50 return res.status(400).json({ message: 'タイトルを入力してください' })51 }52
53 await task.update({54 title,55 description: String(body.description ?? ''),56 done: Boolean(body.done),57 })58
59 res.json(task)60})61
62router.delete('/:id', async (req, res) => {63 const task = await Task.findByPk(req.params.id)64
65 if (!task) {66 return res.status(404).json({ message: 'タスクが見つかりません' })67 }68
69 await task.destroy()70
71 res.status(204).end()72})73
2174export default router作成(POST /tasks)
Section titled “作成(POST /tasks)”sequenceDiagram
participant Client as クライアント
participant API as Web API
participant DB as データベース
Client->>API: POST /tasks<br>{"title":"本を返す","description":"図書館へ"}
API->>API: タイトルが空でないか確かめる
API->>DB: INSERT INTO task ...
DB-->>API: 作成した行(id が決まる)
API-->>Client: 201 Created<br>{"id":4,"title":"本を返す",...}
req.bodyに、express.json()が JavaScript の値に戻した本文が入っています。本文が JSON でないとき(Content-Typeが違う、本文が無い)はundefinedになるので、req.body ?? {}で空のオブジェクトとして扱いますString(body.title ?? '').trim()で、titleが無いときも空文字として扱い、前後の空白を取り除きます- タイトルが空なら、データベースに入れる前に
400とメッセージを返します。入力の確認は Web API で必ず行います。クライアントの画面を通さずに、直接 Web API にリクエストを送ることもできるからです Task.create()で行を作ります。ID はデータベースが決めるので、作成したタスク(ID 入り)をそのまま返します。作成したときのステータスコードは201です
更新(PUT /tasks/:id)
Section titled “更新(PUT /tasks/:id)”- まず
findByPkで対象を探し、無ければ404を返します - 入力の確認は作成と同じです
task.update()で値を書き換えて保存し、更新後のタスクを返します
削除(DELETE /tasks/:id)
Section titled “削除(DELETE /tasks/:id)”- 対象が無ければ
404を返します task.destroy()で削除します- 返す内容が無いので、
res.status(204).end()で本文の無い204 No Contentを返します
POST・PUT・DELETE はブラウザのアドレスバーからは送れないので、開発者ツールのコンソールから fetch で送ってみます。CORS で許可しているオリジンから送るために、クライアントの画面 http://localhost:5173/ を開いた状態でコンソールに入力してください。
作成します。
const response = await fetch('http://localhost:3000/tasks', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title: '本を返す', description: '図書館へ' }),})console.log(response.status, await response.json())201 と、id の入ったタスクが表示されます。表示された id を使って、更新と削除も試します(例では 4)。
const response = await fetch('http://localhost:3000/tasks/4', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title: '本を返す', description: '図書館へ', done: true }),})console.log(response.status, await response.json())const response = await fetch('http://localhost:3000/tasks/4', { method: 'DELETE' })console.log(response.status)タイトルを空にして送ると 400 と { message: 'タイトルを入力してください' } が返ることも確かめましょう。
プリフライトリクエスト
Section titled “プリフライトリクエスト”Network を見ると、POST や PUT の前に OPTIONS というリクエストが送られていることに気づきます。
sequenceDiagram participant Browser as ブラウザ<br>(http://localhost:5173) participant API as Web API<br>(http://localhost:3000) Browser->>API: OPTIONS /tasks/4<br>Access-Control-Request-Method: PUT<br>Access-Control-Request-Headers: content-type API-->>Browser: 204 No Content<br>Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE<br>Access-Control-Allow-Headers: content-type Browser->>API: PUT /tasks/4(本当のリクエスト) API-->>Browser: 200 OK
JSON を送るリクエスト(Content-Type: application/json)や、PUT・DELETE のリクエストは、データを書き換える可能性があります。そこでブラウザは、本当のリクエストを送る前に「このメソッドとヘッダーで送ってよいか」を OPTIONS で問い合わせます。これを プリフライトリクエスト と呼びます。
app.use(cors(...)) で付けた cors のミドルウェアは、この問い合わせ(OPTIONS)にも自動で答え、ルートまで進ませずに 204 を返します。許可するメソッドを変えたいときは methods、ヘッダーを変えたいときは allowedHeaders を指定します。allowedHeaders を指定しないときは、ブラウザが問い合わせてきたヘッダー(Access-Control-Request-Headers)をそのまま許可します(cors のドキュメント)。
クライアントから作成・更新・削除する
Section titled “クライアントから作成・更新・削除する”ここからは client のフォルダで作業します。
Web API を呼び出す関数
Section titled “Web API を呼び出す関数”src/api.js に、作成・更新・削除の関数を足します。
client/src/api.js を変更する
Section titled “client/src/api.js を変更する”11const API_URL = 'http://localhost:3000'22
3async function request(path) {4 const response = await fetch(`${API_URL}${path}`)3async function request(path, options = {}) {4 const response = await fetch(`${API_URL}${path}`, options)55
66 // 404 や 500 でも fetch はエラーにならないので、ok(200 番台か)を自分で確かめる77 if (!response.ok) {99 throw new Error(body?.message ?? `${response.status} ${response.statusText}`)1010 }1111
12 // 204 No Content は本文が無いので、JSON として読まない13 if (response.status === 204) {14 return null15 }16
1217 return response.json()1318}1924export async function getTask(id) {2025 return request(`/tasks/${id}`)2126}27
28export async function createTask(task) {29 return request('/tasks', {30 method: 'POST',31 headers: { 'Content-Type': 'application/json' },32 body: JSON.stringify(task),33 })34}35
36export async function updateTask(task) {37 return request(`/tasks/${task.id}`, {38 method: 'PUT',39 headers: { 'Content-Type': 'application/json' },40 body: JSON.stringify(task),41 })42}43
44export async function deleteTask(id) {45 return request(`/tasks/${id}`, {46 method: 'DELETE',47 })48}request()に、fetchの第 2 引数(options)を渡せるようにしましたmethodで HTTP メソッドを指定します。省略するとGETです- JSON を送るときは、
headersで'Content-Type': 'application/json'を付け、bodyにJSON.stringify()した文字列を入れます。Content-Typeを付けないと、Web API は本文を JSON として読めません - 削除の
204 No Contentには本文が無いので、response.json()を呼ぶとエラーになります。204のときはnullを返すようにしています
タスク作成の画面を足します。
| パス | コンポーネント | 画面名 |
|---|---|---|
/ |
TaskCollection |
タスク一覧 |
🆕 /tasks/new |
TaskCreate |
タスク作成 |
/tasks/:taskId |
TaskSingle |
タスク詳細・編集・削除 |
client/src/App.jsx を変更する
Section titled “client/src/App.jsx を変更する”11import { BrowserRouter, Route, Routes } from 'react-router-dom'22import TaskCollection from './routes/TaskCollection'3import TaskCreate from './routes/TaskCreate'34import TaskSingle from './routes/TaskSingle'45
56function App() {78<BrowserRouter>89 <Routes>910 <Route path="/" element={<TaskCollection />} />11 <Route path="/tasks/new" element={<TaskCreate />} />1012 <Route path="/tasks/:taskId" element={<TaskSingle />} />1113 </Routes>1214</BrowserRouter>client/src/routes/TaskCreate.jsx を作成する
Section titled “client/src/routes/TaskCreate.jsx を作成する”1import { useState } from 'react'2import { Link, useNavigate } from 'react-router-dom'3import { createTask } from '../api'4
5function TaskCreate() {6 const navigate = useNavigate()7 const [values, setValues] = useState({8 title: '',9 description: '',10 })11 const [saving, setSaving] = useState(false)12 const [error, setError] = useState(null)13
14 async function handleSubmit(event) {15 event.preventDefault()16 setSaving(true)17 setError(null)18 try {19 const task = await createTask(values)20 navigate(`/tasks/${task.id}`)21 } catch (error) {22 setError(error)23 } finally {24 setSaving(false)25 }26 }27
28 return (29 <div>30 <h1>タスク作成</h1>31 {error && <p>エラーが発生しました: {error.message}</p>}32 <form onSubmit={handleSubmit}>33 <div>34 <label>35 タイトル:36 <input37 type="text" name="title" value={values.title}38 onChange={(event) => setValues({ ...values, title: event.target.value })} />39 </label>40 </div>41 <div>42 <label>43 メモ:44 <textarea45 name="description" value={values.description}46 onChange={(event) => setValues({ ...values, description: event.target.value })} />47 </label>48 </div>49 <button type="submit" disabled={saving}>作成</button>50 </form>51 <hr />52 <Link to="/">タスク一覧に戻る</Link>53 </div>54 )55}56
57export default TaskCreate- フォームの書き方は フォーム と同じです
createTask()は、Web API が返した作成済みのタスクを返します。そのidを使って、作成したタスクの詳細の画面に移りますsavingがtrueの間はボタンを押せないようにして、二重に送信するのを防ぎます- タイトルが空のときは Web API が
400を返し、api.jsがそのメッセージでエラーを投げるので、「エラーが発生しました: タイトルを入力してください」と表示されます
一覧から作成の画面に移れるようにします。
client/src/routes/TaskCollection.jsx を変更する
Section titled “client/src/routes/TaskCollection.jsx を変更する”2727return (2828 <div>2929 <h1>タスク一覧</h1>30 <p>31 <Link to="/tasks/new">新規作成</Link>32 </p>3033 {loading && <p>読み込み中...</p>}3134 {error && <p>エラーが発生しました: {error.message}</p>}3235 {!loading && !error && tasks.length < 1 && <p>タスクがありません</p>}タスクの更新と削除
Section titled “タスクの更新と削除”詳細の画面を、編集できるフォームに変えます。
client/src/routes/TaskSingle.jsx を変更する
Section titled “client/src/routes/TaskSingle.jsx を変更する”11import { useEffect, useState } from 'react'2import { Link, useParams } from 'react-router-dom'3import { getTask } from '../api'2import { Link, useNavigate, useParams } from 'react-router-dom'3import { deleteTask, getTask, updateTask } from '../api'44
55function TaskSingle() {66 const params = useParams()7 const navigate = useNavigate()78 const [task, setTask] = useState(null)89 const [loading, setLoading] = useState(false)910 const [error, setError] = useState(null)2526 load(params.taskId)2627}, [params.taskId])2728
29async function handleSubmit(event) {30 event.preventDefault()31 setLoading(true)32 setError(null)33 try {34 const updated = await updateTask(task)35 setTask(updated)36 alert('保存しました')37 } catch (error) {38 setError(error)39 } finally {40 setLoading(false)41 }42}43
44async function handleDelete() {45 if (!confirm('削除しますか?')) return46 setLoading(true)47 setError(null)48 try {49 await deleteTask(task.id)50 navigate('/')51 } catch (error) {52 setError(error)53 setLoading(false)54 }55}56
2857return (2958 <div>3059 <h1>タスク詳細</h1>3160 {loading && <p>読み込み中...</p>}3261 {error && <p>エラーが発生しました: {error.message}</p>}3362 {task && (34 <dl>35 <dt>ID</dt>36 <dd>{task.id}</dd>37 <dt>タイトル</dt>38 <dd>{task.title}</dd>39 <dt>メモ</dt>40 <dd>{task.description || '(なし)'}</dd>41 <dt>状態</dt>42 <dd>{task.done ? '完了' : '未完了'}</dd>43 </dl>63 <form onSubmit={handleSubmit}>64 <p>ID: {task.id}</p>65 <div>66 <label>67 タイトル:68 <input69 type="text" name="title" value={task.title}70 onChange={(event) => setTask({ ...task, title: event.target.value })} />71 </label>72 </div>73 <div>74 <label>75 メモ:76 <textarea77 name="description" value={task.description}78 onChange={(event) => setTask({ ...task, description: event.target.value })} />79 </label>80 </div>81 <div>82 <label>83 <input84 type="checkbox" name="done" checked={task.done}85 onChange={(event) => setTask({ ...task, done: event.target.checked })} />86 完了87 </label>88 </div>89 <button type="submit" disabled={loading}>保存</button>90 <button type="button" onClick={handleDelete} disabled={loading}>削除</button>91 </form>4492 )}4593 <hr />4694 <Link to="/">タスク一覧に戻る</Link>- 入力欄の値は
taskの状態にそのまま入れます。この時点では、まだデータベースは変わっていません(画面の写しを書き換えているだけです) - 「保存」を押すと
updateTask(task)で Web API に送り、返ってきた更新後のタスクでtaskを置き換えます。データベースに保存された値を画面に出すためです - 「削除」は
confirm()で確認してからdeleteTask()を呼び、成功したら一覧に戻ります - チェックボックスは
valueではなくcheckedとevent.target.checkedを使います
sequenceDiagram actor User as 利用者 participant Client as クライアント participant API as Web API participant DB as データベース User->>Client: タイトルを入力する Client->>Client: setTask で画面の写しを書き換える User->>Client: 「保存」を押す Client->>API: PUT /tasks/1 API->>DB: UPDATE task SET ... API-->>Client: 200 OK(更新後のタスク) Client->>Client: setTask(updated)
Web API とクライアントの両方を起動して、http://localhost:5173/ で次のことを確かめます。
- 「新規作成」からタスクを作成すると、作成したタスクの詳細が表示される
- タイトルを空にして作成すると、エラーのメッセージが表示される
- 詳細でタイトル・メモ・完了を変えて「保存」し、一覧に戻ると変更が反映されている
- 「削除」で削除すると一覧に戻り、一覧から消えている
- ブラウザを再読み込みしても、Web API を再起動しても、データが残っている(データベースに保存されている)
SQLiteBrowser などで database.sqlite を開き、画面の操作が task テーブルに反映されていることも確かめてみましょう。
この章では、クライアント・Web API・データベースをつないで、CRUD のそろった Web アプリケーションを作りました。
flowchart LR
subgraph client["client(React)"]
Screen["画面<br>state は写し"] --> ApiJs["api.js<br>fetch"]
end
subgraph api["api(Express)"]
Routes["ルート<br>入力の確認"] --> Model["Task モデル<br>Sequelize"]
end
DB[("database.sqlite<br>本物のデータ")]
ApiJs -->|"HTTP + JSON<br>CORS"| Routes
Model -->|SQL| DB
- 作成は
POST、更新はPUT、削除はDELETEで、JSON を送るときはContent-TypeとJSON.stringify()を使う - 入力の確認は Web API で必ず行い、問題があれば
400とメッセージを返す - クライアントは Web API の結果(ステータスコードと本文)を見て、成功・失敗を表示する
- 画面の state は写しなので、保存したら Web API が返した値で置き換える
次の章では、顧客管理アプリ(フロントエンド版) で localStorage に保存していた部分を、この章と同じ形の Web API とデータベースに置き換えた完全版を作ります。
この節を終えたときのディレクトリ
Section titled “この節を終えたときのディレクトリ”import { readFileSync } from 'node:fs'import sqlite3 from 'sqlite3'
// init.sql を読み込んで、database.sqlite に流す(テーブルを作り直して、最初のデータを入れる)const sql = readFileSync(new URL('./init.sql', import.meta.url), 'utf8')const db = new sqlite3.Database('./database.sqlite')
db.exec(sql, (error) => { if (error) { console.error(error) process.exitCode = 1 } else { console.log('database.sqlite を初期化しました') } db.close()})DROP TABLE IF EXISTS task;
CREATE TABLE task ( id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, description TEXT NOT NULL DEFAULT '', done INTEGER NOT NULL DEFAULT 0);
INSERT INTO task (title, description, done) VALUES ('牛乳を買う', '帰りにスーパーで 1 本買う', 0), ('部屋を掃除する', '', 1), ('レポートを書く', '金曜日までに提出する', 0);import { DataTypes } from 'sequelize'import { sequelize } from '../db.js'
const Task = sequelize.define('Task', { id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true, }, title: { type: DataTypes.STRING, allowNull: false, }, description: { type: DataTypes.STRING, allowNull: false, defaultValue: '', }, done: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false, },}, { tableName: 'task', timestamps: false,})
export default Taskimport express from 'express'import Task from '../models/Task.js'
const router = express.Router()
router.get('/', async (req, res) => { const tasks = await Task.findAll({ order: [['id', 'ASC']] }) res.json(tasks)})
router.get('/:id', async (req, res) => { const task = await Task.findByPk(req.params.id)
if (!task) { return res.status(404).json({ message: 'タスクが見つかりません' }) }
res.json(task)})
router.post('/', async (req, res) => { // 本文が JSON でないときは req.body が undefined なので、空のオブジェクトとして扱う const body = req.body ?? {} const title = String(body.title ?? '').trim()
if (title === '') { return res.status(400).json({ message: 'タイトルを入力してください' }) }
const task = await Task.create({ title, description: String(body.description ?? ''), done: Boolean(body.done), })
res.status(201).json(task)})
router.put('/:id', async (req, res) => { const task = await Task.findByPk(req.params.id)
if (!task) { return res.status(404).json({ message: 'タスクが見つかりません' }) }
const body = req.body ?? {} const title = String(body.title ?? '').trim()
if (title === '') { return res.status(400).json({ message: 'タイトルを入力してください' }) }
await task.update({ title, description: String(body.description ?? ''), done: Boolean(body.done), })
res.json(task)})
router.delete('/:id', async (req, res) => { const task = await Task.findByPk(req.params.id)
if (!task) { return res.status(404).json({ message: 'タスクが見つかりません' }) }
await task.destroy()
res.status(204).end()})
export default routerimport { Sequelize } from 'sequelize'
export const sequelize = new Sequelize({ dialect: 'sqlite', storage: './database.sqlite', logging: false,})import cors from 'cors'import express from 'express'import tasks from './routes/tasks.js'
const app = express()
app.use(cors({ origin: 'http://localhost:5173',}))// リクエストの本文の JSON を読み、req.body に入れるapp.use(express.json())
app.get('/', (req, res) => { res.send('Hello Express!')})
app.use('/tasks', tasks)
// どのルートにも当てはまらなかったリクエストapp.use((req, res) => { res.status(404).json({ message: '見つかりません' })})
// ルートの中で起きたエラー(データベースのエラーなど)は、ここに届くapp.use((err, req, res, next) => { // express.json() が本文を読めなかったとき(JSON の書き方の誤りなど)は、err.status に 400 番台が入っている if (err.status >= 400 && err.status < 500) { return res.status(err.status).json({ message: 'リクエストの本文を読めませんでした' }) }
console.error(err) res.status(500).json({ message: 'サーバーでエラーが発生しました' })})
app.listen(3000, (error) => { if (error) { throw error } console.log('Server is running on http://localhost:3000')})node_modules/*.sqlite(npm install が書き出すファイルです。長いので、ここでは中身を省いています。ZIP には入っています){ "name": "api", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev": "node --watch src/index.js", "start": "node src/index.js", "db:init": "node db/init.js" }, "keywords": [], "author": "", "license": "ISC", "type": "module", "dependencies": { "cors": "^2.8.6", "express": "^5.3.0", "sequelize": "^6.37.8", "sqlite3": "^6.0.1" }}<svg xmlns="http://www.w3.org/2000/svg" width="48" height="46" fill="none" viewBox="0 0 48 46"><path fill="#863bff" d="M25.946 44.938c-.664.845-2.021.375-2.021-.698V33.937a2.26 2.26 0 0 0-2.262-2.262H10.287c-.92 0-1.456-1.04-.92-1.788l7.48-10.471c1.07-1.497 0-3.578-1.842-3.578H1.237c-.92 0-1.456-1.04-.92-1.788L10.013.474c.214-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.471c-1.07 1.498 0 3.579 1.842 3.579h11.377c.943 0 1.473 1.088.89 1.83L25.947 44.94z" style="fill:#863bff;fill:color(display-p3 .5252 .23 1);fill-opacity:1"/><mask id="a" width="48" height="46" x="0" y="0" maskUnits="userSpaceOnUse" style="mask-type:alpha"><path fill="#000" d="M25.842 44.938c-.664.844-2.021.375-2.021-.698V33.937a2.26 2.26 0 0 0-2.262-2.262H10.183c-.92 0-1.456-1.04-.92-1.788l7.48-10.471c1.07-1.498 0-3.579-1.842-3.579H1.133c-.92 0-1.456-1.04-.92-1.787L9.91.473c.214-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.471c-1.07 1.498 0 3.578 1.842 3.578h11.377c.943 0 1.473 1.088.89 1.832L25.843 44.94z" style="fill:#000;fill-opacity:1"/></mask><g mask="url(#a)"><g filter="url(#b)"><ellipse cx="5.508" cy="14.704" fill="#ede6ff" rx="5.508" ry="14.704" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -4.47 31.516)"/></g><g filter="url(#c)"><ellipse cx="10.399" cy="29.851" fill="#ede6ff" rx="10.399" ry="29.851" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -39.328 7.883)"/></g><g filter="url(#d)"><ellipse cx="5.508" cy="30.487" fill="#7e14ff" rx="5.508" ry="30.487" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.814 -25.913 -14.639)scale(1 -1)"/></g><g filter="url(#e)"><ellipse cx="5.508" cy="30.599" fill="#7e14ff" rx="5.508" ry="30.599" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.814 -32.644 -3.334)scale(1 -1)"/></g><g filter="url(#f)"><ellipse cx="5.508" cy="30.599" fill="#7e14ff" rx="5.508" ry="30.599" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -34.34 30.47)"/></g><g filter="url(#g)"><ellipse cx="14.072" cy="22.078" fill="#ede6ff" rx="14.072" ry="22.078" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="rotate(93.35 24.506 48.493)scale(-1 1)"/></g><g filter="url(#h)"><ellipse cx="3.47" cy="21.501" fill="#7e14ff" rx="3.47" ry="21.501" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.009 28.708 47.59)scale(-1 1)"/></g><g filter="url(#i)"><ellipse cx="3.47" cy="21.501" fill="#7e14ff" rx="3.47" ry="21.501" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.009 28.708 47.59)scale(-1 1)"/></g><g filter="url(#j)"><ellipse cx=".387" cy="8.972" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(39.51 .387 8.972)"/></g><g filter="url(#k)"><ellipse cx="47.523" cy="-6.092" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 47.523 -6.092)"/></g><g filter="url(#l)"><ellipse cx="41.412" cy="6.333" fill="#47bfff" rx="5.971" ry="9.665" style="fill:#47bfff;fill:color(display-p3 .2799 .748 1);fill-opacity:1" transform="rotate(37.892 41.412 6.333)"/></g><g filter="url(#m)"><ellipse cx="-1.879" cy="38.332" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 -1.88 38.332)"/></g><g filter="url(#n)"><ellipse cx="-1.879" cy="38.332" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 -1.88 38.332)"/></g><g filter="url(#o)"><ellipse cx="35.651" cy="29.907" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 35.651 29.907)"/></g><g filter="url(#p)"><ellipse cx="38.418" cy="32.4" fill="#47bfff" rx="5.971" ry="15.297" style="fill:#47bfff;fill:color(display-p3 .2799 .748 1);fill-opacity:1" transform="rotate(37.892 38.418 32.4)"/></g></g><defs><filter id="b" width="60.045" height="41.654" x="-19.77" y="16.149" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="7.659"/></filter><filter id="c" width="90.34" height="51.437" x="-54.613" y="-7.533" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="7.659"/></filter><filter id="d" width="79.355" height="29.4" x="-49.64" y="2.03" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="4.596"/></filter><filter id="e" width="79.579" height="29.4" x="-45.045" y="20.029" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="4.596"/></filter><filter id="f" width="79.579" height="29.4" x="-43.513" y="21.178" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="4.596"/></filter><filter id="g" width="74.749" height="58.852" x="15.756" y="-17.901" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="7.659"/></filter><filter id="h" width="61.377" height="25.362" x="23.548" y="2.284" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="4.596"/></filter><filter id="i" width="61.377" height="25.362" x="23.548" y="2.284" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="4.596"/></filter><filter id="j" width="56.045" height="63.649" x="-27.636" y="-22.853" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="4.596"/></filter><filter id="k" width="54.814" height="64.646" x="20.116" y="-38.415" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="4.596"/></filter><filter id="l" width="33.541" height="35.313" x="24.641" y="-11.323" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="4.596"/></filter><filter id="m" width="54.814" height="64.646" x="-29.286" y="6.009" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="4.596"/></filter><filter id="n" width="54.814" height="64.646" x="-29.286" y="6.009" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="4.596"/></filter><filter id="o" width="54.814" height="64.646" x="8.244" y="-2.416" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="4.596"/></filter><filter id="p" width="39.409" height="43.623" x="18.713" y="10.588" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="4.596"/></filter></defs></svg><svg xmlns="http://www.w3.org/2000/svg"> <symbol id="bluesky-icon" viewBox="0 0 16 17"> <g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g> <defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs> </symbol> <symbol id="discord-icon" viewBox="0 0 20 19"> <path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/> </symbol> <symbol id="documentation-icon" viewBox="0 0 21 20"> <path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/> <path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/> <path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/> </symbol> <symbol id="github-icon" viewBox="0 0 19 19"> <path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/> </symbol> <symbol id="social-icon" viewBox="0 0 20 20"> <path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/> <path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/> </symbol> <symbol id="x-icon" viewBox="0 0 19 19"> <path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/> </symbol></svg>import { useEffect, useState } from 'react'import { Link } from 'react-router-dom'import { getTasks } from '../api'
function TaskCollection() { const [tasks, setTasks] = useState([]) const [loading, setLoading] = useState(false) const [error, setError] = useState(null)
async function load() { setLoading(true) setError(null) try { const tasks = await getTasks() setTasks(tasks) } catch (error) { setError(error) } finally { setLoading(false) } }
useEffect(() => { load() }, [])
return ( <div> <h1>タスク一覧</h1> <p> <Link to="/tasks/new">新規作成</Link> </p> {loading && <p>読み込み中...</p>} {error && <p>エラーが発生しました: {error.message}</p>} {!loading && !error && tasks.length < 1 && <p>タスクがありません</p>} <ul> {tasks.map((task) => ( <li key={task.id}> {task.done ? '✅' : '⬜'} <Link to={`/tasks/${task.id}`}>{task.title}</Link> </li> ))} </ul> </div> )}
export default TaskCollectionimport { useState } from 'react'import { Link, useNavigate } from 'react-router-dom'import { createTask } from '../api'
function TaskCreate() { const navigate = useNavigate() const [values, setValues] = useState({ title: '', description: '', }) const [saving, setSaving] = useState(false) const [error, setError] = useState(null)
async function handleSubmit(event) { event.preventDefault() setSaving(true) setError(null) try { const task = await createTask(values) navigate(`/tasks/${task.id}`) } catch (error) { setError(error) } finally { setSaving(false) } }
return ( <div> <h1>タスク作成</h1> {error && <p>エラーが発生しました: {error.message}</p>} <form onSubmit={handleSubmit}> <div> <label> タイトル: <input type="text" name="title" value={values.title} onChange={(event) => setValues({ ...values, title: event.target.value })} /> </label> </div> <div> <label> メモ: <textarea name="description" value={values.description} onChange={(event) => setValues({ ...values, description: event.target.value })} /> </label> </div> <button type="submit" disabled={saving}>作成</button> </form> <hr /> <Link to="/">タスク一覧に戻る</Link> </div> )}
export default TaskCreateimport { useEffect, useState } from 'react'import { Link, useNavigate, useParams } from 'react-router-dom'import { deleteTask, getTask, updateTask } from '../api'
function TaskSingle() { const params = useParams() const navigate = useNavigate() const [task, setTask] = useState(null) const [loading, setLoading] = useState(false) const [error, setError] = useState(null)
async function load(id) { setLoading(true) setError(null) try { const task = await getTask(id) setTask(task) } catch (error) { setError(error) } finally { setLoading(false) } }
useEffect(() => { load(params.taskId) }, [params.taskId])
async function handleSubmit(event) { event.preventDefault() setLoading(true) setError(null) try { const updated = await updateTask(task) setTask(updated) alert('保存しました') } catch (error) { setError(error) } finally { setLoading(false) } }
async function handleDelete() { if (!confirm('削除しますか?')) return setLoading(true) setError(null) try { await deleteTask(task.id) navigate('/') } catch (error) { setError(error) setLoading(false) } }
return ( <div> <h1>タスク詳細</h1> {loading && <p>読み込み中...</p>} {error && <p>エラーが発生しました: {error.message}</p>} {task && ( <form onSubmit={handleSubmit}> <p>ID: {task.id}</p> <div> <label> タイトル: <input type="text" name="title" value={task.title} onChange={(event) => setTask({ ...task, title: event.target.value })} /> </label> </div> <div> <label> メモ: <textarea name="description" value={task.description} onChange={(event) => setTask({ ...task, description: event.target.value })} /> </label> </div> <div> <label> <input type="checkbox" name="done" checked={task.done} onChange={(event) => setTask({ ...task, done: event.target.checked })} /> 完了 </label> </div> <button type="submit" disabled={loading}>保存</button> <button type="button" onClick={handleDelete} disabled={loading}>削除</button> </form> )} <hr /> <Link to="/">タスク一覧に戻る</Link> </div> )}
export default TaskSingleconst API_URL = 'http://localhost:3000'
async function request(path, options = {}) { const response = await fetch(`${API_URL}${path}`, options)
// 404 や 500 でも fetch はエラーにならないので、ok(200 番台か)を自分で確かめる if (!response.ok) { const body = await response.json().catch(() => null) throw new Error(body?.message ?? `${response.status} ${response.statusText}`) }
// 204 No Content は本文が無いので、JSON として読まない if (response.status === 204) { return null }
return response.json()}
export async function getTasks() { return request('/tasks')}
export async function getTask(id) { return request(`/tasks/${id}`)}
export async function createTask(task) { return request('/tasks', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(task), })}
export async function updateTask(task) { return request(`/tasks/${task.id}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(task), })}
export async function deleteTask(id) { return request(`/tasks/${id}`, { method: 'DELETE', })}import { BrowserRouter, Route, Routes } from 'react-router-dom'import TaskCollection from './routes/TaskCollection'import TaskCreate from './routes/TaskCreate'import TaskSingle from './routes/TaskSingle'
function App() { return ( <BrowserRouter> <Routes> <Route path="/" element={<TaskCollection />} /> <Route path="/tasks/new" element={<TaskCreate />} /> <Route path="/tasks/:taskId" element={<TaskSingle />} /> </Routes> </BrowserRouter> )}
export default Appimport { StrictMode } from 'react'import { createRoot } from 'react-dom/client'import App from './App.jsx'
createRoot(document.getElementById('root')).render( <StrictMode> <App /> </StrictMode>,)# Logslogs*.lognpm-debug.log*yarn-debug.log*yarn-error.log*pnpm-debug.log*lerna-debug.log*
node_modulesdistdist-ssr*.local
# Editor directories and files.vscode/*!.vscode/extensions.json.idea.DS_Store*.suo*.ntvs**.njsproj*.sln*.sw?{ "$schema": "./node_modules/oxlint/configuration_schema.json", "plugins": ["react", "oxc"], "rules": { "react/rules-of-hooks": "error", "react/only-export-components": ["warn", { "allowConstantExport": true }] }}<!doctype html><html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="/favicon.svg" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>client</title> </head> <body> <div id="root"></div> <script type="module" src="/src/main.jsx"></script> </body></html>(npm install が書き出すファイルです。長いので、ここでは中身を省いています。ZIP には入っています){ "name": "client", "private": true, "version": "0.0.0", "type": "module", "scripts": { "dev": "vite", "build": "vite build", "lint": "oxlint", "preview": "vite preview" }, "dependencies": { "react": "^19.3.1", "react-dom": "^19.3.1", "react-router-dom": "^7.18.7" }, "devDependencies": { "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0", "@vitejs/plugin-react": "^6.3.0", "oxlint": "^1.94.0", "vite": "^8.4.0" }}import react from '@vitejs/plugin-react'import { defineConfig } from 'vite'
// https://vite.dev/config/export default defineConfig({ plugins: [react()],})よくある質問
Section titled “よくある質問”作成・更新をすると「エラーが発生しました: Unexpected end of JSON input」と出ます
Web API が本文の無いレスポンスを返したのに、response.json() を呼んでいる可能性があります。api.js の 204 の確認を書き忘れていないかを確かめてください。
PUT と PATCH は何が違うのですか?
PUT は「この内容で置き換える」、PATCH は「この部分だけ変える」という意味で使い分けるのが一般的です。この節の PUT /tasks/:id は、タイトル・メモ・完了をすべて送って置き換えています。完了だけを切り替える Web API を作るなら、PATCH を使うのが自然です。
一覧の画面で、チェックボックスで完了を切り替えられるようにしたいです
一覧の各行にチェックボックスを置き、変更されたら updateTask({ ...task, done: event.target.checked }) を呼んでから、一覧を読み込み直す(load() を呼ぶ)と作れます。練習としてやってみてください。