AI Bültenim Yapay Zeka Haber Portalı Logosu
Kod

Next.js server action form

Zod doğrulamalı Next.js server action form örneği ister.

Kod Prompt Kütüphanesi için temsili kategori görseli

Prompt Metni

Next.js App Router ve TypeScript kullanarak e-posta abonelik formu oluştur.

Gereksinimler:
- Form, ayrı bir Server Action çağırmalı; istemcide fetch kullanılmamalı.
- E-posta Zod ile doğrulanmalı.
- Alan hatası ve başarı durumu tip güvenli biçimde gösterilmeli.
- Veritabanı işlemi yerine kısa bir örnek başarı akışı yeterli.
- Yalnızca actions.ts ve form.tsx dosyalarını ver.

Prompt Sonucu

app/subscribe/actions.ts 'use server' import { z } from 'zod' const schema = z.object({ email: z.string().email('Geçerli bir e-posta girin.'), }) export type FormState = { status: 'idle' | 'error' | 'success' message?: string } export async function subscribe( _previousState: FormState, formData: FormData ): Promise<FormState> { const result = schema.safeParse({ email: formData.get('email') }) if (!result.success) { return { status: 'error', message: result.error.flatten().fieldErrors.email?.[0], } } // Burada result.data.email veritabanına kaydedilebilir. return { status: 'success', message: 'Aboneliğiniz alındı.' } } app/subscribe/form.tsx 'use client' import { useActionState } from 'react' import { subscribe, type FormState } from './actions' const initialState: FormState = { status: 'idle' } export function SubscribeForm() { const [state, action, pending] = useActionState(subscribe, initialState) return ( <form action={action}> <label htmlFor="email">E-posta</label> <input id="email" name="email" type="email" required /> <button disabled={pending}> {pending ? 'Gönderiliyor…' : 'Abone ol'} </button> {state.message && ( <p role={state.status === 'error' ? 'alert' : 'status'}> {state.message} </p> )} </form> ) }

AI Bültenim prompt kütüphanesi — Tüm promptlar