Newer
Older
WebAppTemplate / flask-react-app / frontend / src / App.tsx
// - GET /api/health を叩いて結果表示
// - POST /api/echo を叩いて結果表示

import { useState } from "react";

type HealthResponse = {
  ok: boolean;
  message: string;
};

type EchoResponse = {
  ok: boolean;
  you_sent: unknown;
};

export default function App() {
  // API結果表示用(型付き)
  const [health, setHealth] = useState<HealthResponse | null>(null);
  const [echo, setEcho] = useState<EchoResponse | null>(null);

  const callHealth = async () => {
    const res = await fetch("/api/health");
    const json: HealthResponse = await res.json();
    setHealth(json);
  };

  const callEcho = async () => {
    const payload = { hello: "world", at: new Date().toISOString() };

    const res = await fetch("/api/echo", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload)
    });

    const json: EchoResponse = await res.json();
    setEcho(json);
  };

  return (
    <main className="wrap">
      <h1>Flask + React + TypeScript (Vite) Starter</h1>

      <section className="card">
        <h2>GET /api/health</h2>
        <button onClick={callHealth}>health</button>
        <pre>{health ? JSON.stringify(health, null, 2) : ""}</pre>
      </section>

      <section className="card">
        <h2>POST /api/echo</h2>
        <button onClick={callEcho}>echo</button>
        <pre>{echo ? JSON.stringify(echo, null, 2) : ""}</pre>
      </section>
    </main>
  );
}