Files
gutscheintracker/app/contacts/page.tsx
T

73 lines
2.9 KiB
TypeScript

"use client";
import { useEffect, useState } from "react";
import Link from "next/link";
import { validateContact } from "@/lib/contacts";
type Contact = { id: number; name: string; email: string | null; telegramChatId: string | null };
export default function ContactsPage() {
const [contacts, setContacts] = useState<Contact[]>([]);
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [telegramChatId, setTelegramChatId] = useState("");
const [errors, setErrors] = useState<string[]>([]);
async function load() {
const res = await fetch("/api/contacts");
if (res.ok) setContacts(await res.json());
}
useEffect(() => { load(); }, []);
async function onSubmit(e: React.FormEvent) {
e.preventDefault();
const input = { name, email: email || null, telegramChatId: telegramChatId || null };
const errs = validateContact(input);
setErrors(errs);
if (errs.length) return;
const res = await fetch("/api/contacts", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(input),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
setErrors(data.errors ?? ["speichern"]);
return;
}
setName(""); setEmail(""); setTelegramChatId(""); setErrors([]);
load();
}
return (
<main className="mx-auto max-w-xl space-y-4 p-6">
<Link href="/" className="text-sm underline">← Zurück</Link>
<h1 className="text-xl font-bold">Kontakte</h1>
<form onSubmit={onSubmit} className="space-y-3" noValidate>
<div>
<label htmlFor="name" className="block text-sm font-medium">Name</label>
<input id="name" value={name} onChange={(e) => setName(e.target.value)} className="mt-1 w-full rounded border px-3 py-2" />
</div>
<div>
<label htmlFor="email" className="block text-sm font-medium">E-Mail</label>
<input id="email" type="email" value={email} onChange={(e) => setEmail(e.target.value)} className="mt-1 w-full rounded border px-3 py-2" />
</div>
<div>
<label htmlFor="telegramChatId" className="block text-sm font-medium">Telegram-Chat-ID</label>
<input id="telegramChatId" value={telegramChatId} onChange={(e) => setTelegramChatId(e.target.value)} className="mt-1 w-full rounded border px-3 py-2" />
</div>
{errors.length > 0 && <p className="text-sm text-red-600">Ungültig: {errors.join(", ")}</p>}
<button type="submit" className="rounded bg-black px-4 py-2 text-white">Hinzufügen</button>
</form>
<ul className="divide-y">
{contacts.map((c) => (
<li key={c.id} className="py-2 text-sm">
<span className="font-medium">{c.name}</span>
{c.email && <span> · {c.email}</span>}
{c.telegramChatId && <span> · Telegram {c.telegramChatId}</span>}
</li>
))}
</ul>
</main>
);
}