import { useActionState } from 'react';
function ContactForm() {
const [state, submitAction, isPending] = useActionState(
async (prevState, formData) => {
try {
const response = await fetch('/api/contact', {
method: 'POST',
body: formData,
});
if (!response.ok) {
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at $19.99/month. Cancel anytime
throw new Error('Failed to submit form');
}
return { success: true, message: 'Form submitted successfully!' };
} catch (error) {
return { success: false, error: error.message };
}
},
{ success: false, message: '' }
);
return (
<form action={submitAction}>
<input name="email" type="email" required />
<textarea name="message" required />
<button type="submit" disabled={isPending}>
{isPending ? 'Submitting...' : 'Submit'}
</button>
{state.success && <p style={{ color: 'green' }}>{state.message}</p>}
{state.error && <p style={{ color: 'red' }}>Error: {state.error}</p>}
</form>
);
}