0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Next.js】tableタグ内のリストをPost送信する方法

Posted at

Next.js 19で、商品テーブルの情報をサーバサイドにPOSTする処理を作成するには、以下のようなコードを参考にしてください。ここでは、商品テーブルの情報をクライアントからサーバーにPOSTリクエストとして送信する部分を実装します。

イメージ

image.png

必要な構成

1.商品テーブルのデータをユーザーが入力できるようにする。

2.ユーザーが送信ボタンを押したときに、そのデータをサーバーにPOSTリクエストとして送信する。

3.サーバー側でPOSTリクエストを受け取り、適切に処理する。

1. page.tsx (クライアントサイド)

まず、商品テーブルを表示し、ユーザーが商品名、価格、個数を入力できるようにします。送信ボタンを押すと、サーバー側にPOSTリクエストが送信されます。

app/sample-product-table/table/page.tsx
// app/table/page.tsx
"use client"
import React, { useState } from "react";

interface Product {
    name: string;
    price: string;
    quantity: string;
}

export default function ProductTable() {
    // ★ 初期データ6行分
    const [products, setProducts] = useState<Product[]>([
        { name: "りんご", price: "120", quantity: "10" },
        { name: "バナナ", price: "80", quantity: "5" },
        { name: "ぶどう", price: "300", quantity: "2" },
        { name: "みかん", price: "60", quantity: "20" },
        { name: "メロン", price: "1500", quantity: "1" },
        { name: "スイカ", price: "800", quantity: "3" },
    ]);

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        try {
            const response = await fetch("/api/products", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify(products),
            });

            if (!response.ok) throw new Error("送信に失敗しました");

            alert("送信しました!");
        } catch (error) {
            console.error(error);
            alert("送信中にエラーが発生しました");
        }
    };

    const handleInputChange = (
        index: number,
        field: keyof Product,
        value: string
    ) => {
        const updated = [...products];
        updated[index] = { ...updated[index], [field]: value };
        setProducts(updated);
    };

    return (
        <div>
            <form onSubmit={handleSubmit}>
                <table border={1} cellPadding={4} style={{border:"solid"}}>
                    <thead>
                        <tr>
                            <th style={{border:"solid"}}>商品名</th>
                            <th style={{border:"solid"}}>価格</th>
                            <th style={{border:"solid"}}>個数</th>
                        </tr>
                    </thead>
                    <tbody>
                        {products.map((product, index) => (
                            <tr key={index} style={{border:"solid"}}>
                                <td style={{border:"solid"}}>
                                    <input
                                        type="text"
                                        value={product.name}
                                        onChange={(e) =>
                                            handleInputChange(index, "name", e.target.value)
                                        }
                                    />
                                </td>
                                <td style={{border:"solid"}}>
                                    <input
                                        type="text"
                                        value={product.price}
                                        onChange={(e) =>
                                            handleInputChange(index, "price", e.target.value)
                                        }
                                    />
                                </td>
                                <td style={{border:"solid"}}>
                                    <input
                                        type="text"
                                        value={product.quantity}
                                        onChange={(e) =>
                                            handleInputChange(index, "quantity", e.target.value)
                                        }
                                    />
                                </td>
                            </tr>
                        ))}
                    </tbody>
                </table>

                <button type="submit" style={{ marginTop: "12px",border:"solid",borderColor:"black",backgroundColor:"lightblue" }}>
                    送信
                </button>
            </form>
        </div>
    );
}

2. api/products (サーバサイド)

次に、/api/productsのAPIルートを作成し、POSTリクエストを受け取り、処理します。
サーバー側でリクエストを受けて、必要に応じてデータベースに保存したり、処理を行います。

app/api/products/route.ts
// app/api/products/route.ts
import { NextRequest, NextResponse } from "next/server";

export async function POST(req: NextRequest) {
    try {
        // リクエストボディを取得
        const products = await req.json();
        console.log("ブラウザから受け取ったデータは:" + products);
        // ここでproductsをDBに保存するなどの処理を行う

        // データ処理成功した場合
        return NextResponse.json({ message: "商品データが正常に保存されました" }, { status: 200 });
    } catch (error) {
        console.error(error);
        return NextResponse.json({ message: "エラーが発生しました" }, { status: 500 });
    }
}

詳細説明
1.クライアントサイド (page.tsx)

useStateを使って、テーブルに表示する商品のリストを管理します。
handleInputChangeで、テーブル内の商品情報が変更されるたびに、対応する商品情報を更新します。
■フォームが送信されると、handleSubmitfetchを使ってPOSTリクエストをサーバーに送信します。

2.サーバサイド (route.ts)

■POSTリクエストで送信された商品情報を受け取ります。受け取ったデータはJSONとしてパースされ、必要に応じてデータベースに保存できます。
■エラー処理を行い、成功した場合は200ステータスを返します。

この構成で、クライアントからサーバーへ商品情報をPOSTできるようになります。フォームに入力した商品情報は、送信後にサーバー側で処理されます。

サイト

最新のReact 19の変更点と例

React18の新機能と変更点を実際に手元で動かして理解してみる(自動バッチング, トランジション機能, startTransition(), useTransition(), useDeferredValue())

そうです。わたしがReactをシンプルにするSWRです。

Next.js×SSG解説 ~仕組み・メリット・実装法~

Next.jsを選ぶ理由:Reactとの違いとSSG・CSRの使い分け

FastAPIで作成したデータをVue.jsで表示させる

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?