React hook
Opret en reusable hook til at sende henvendelser:Copy
Ask AI
// hooks/useReplied.ts
import { useState } from 'react';
const API_URL = 'https://www.replied.dk/api/v1/submit/JERES_API_NØGLE';
interface SubmitData {
name: string;
email: string;
phone?: string;
subject?: string;
message: string;
[key: string]: any; // Brugerdefinerede felter
}
export function useReplied() {
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState(false);
async function submit(data: SubmitData) {
setLoading(true);
setError(null);
setSuccess(false);
try {
const res = await fetch(API_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
if (!res.ok) {
const body = await res.json();
throw new Error(body.error || 'Submission failed');
}
setSuccess(true);
return await res.json();
} catch (err: any) {
setError(err.message);
throw err;
} finally {
setLoading(false);
}
}
return { submit, loading, error, success };
}
Kontaktformular-komponent
Copy
Ask AI
// components/ContactForm.tsx
'use client';
import { useState } from 'react';
import { useReplied } from '@/hooks/useReplied';
export function ContactForm() {
const { submit, loading, error, success } = useReplied();
const [form, setForm] = useState({ name: '', email: '', message: '' });
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
await submit(form);
setForm({ name: '', email: '', message: '' });
}
if (success) {
return <p>Tak for din henvendelse! Vi vender tilbage hurtigst muligt.</p>;
}
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={form.name}
onChange={(e) => setForm({ ...form, name: e.target.value })}
placeholder="Navn"
required
/>
<input
type="email"
value={form.email}
onChange={(e) => setForm({ ...form, email: e.target.value })}
placeholder="Email"
required
/>
<textarea
value={form.message}
onChange={(e) => setForm({ ...form, message: e.target.value })}
placeholder="Besked"
required
/>
{error && <p style={{ color: 'red' }}>{error}</p>}
<button type="submit" disabled={loading}>
{loading ? 'Sender...' : 'Send'}
</button>
</form>
);
}
Server-side (Next.js API route)
Hvis I vil sende fra jeres egen backend i stedet for klienten:Copy
Ask AI
// app/api/contact/route.ts
import { NextResponse } from 'next/server';
export async function POST(req: Request) {
const data = await req.json();
const res = await fetch('https://www.replied.dk/api/v1/submit/JERES_API_NØGLE', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
if (!res.ok) {
return NextResponse.json({ error: 'Failed to submit' }, { status: 500 });
}
return NextResponse.json({ success: true });
}
Server-side submission skjuler jeres API-nøgle fra klienten. Anbefalet til produktion.