Within my Nextjs 15 project, I have implemented a contact form as a client component. To enhance security measures, I integrated Google Captcha v3 by following the documentation provided.
Upon submitting the contact form, a submission handler is activated. This handler utilizes a function to generate a Captcha token and then triggers a server action responsible for sending an email to the website owner.
In order to improve the user experience on the frontend, I am leveraging the useActionState hook within the component. By utilizing the values of isPending and state, I can better communicate the server action's status to the user.
The structure of my component is set up as follows:
const initialState = {
status: 'success',
messages: [],
}
const Contact = () => {
const [state, formAction, isPending] = useActionState(sendEmail, initialState)
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault()
const captchaToken = await getCaptchaToken()
const formData = new FormData(event.currentTarget)
formAction(formData, captchaToken)
}
return (
<div>
<h2>
Contact
</h2>
<form onSubmit={handleSubmit}>
<label>
Name
<input
required
type='text'
name='fname'
placeholder='enter your first name'
/>
</label>
<label>
Email
<input
required
type='email'
name='email'
placeholder='enter your email'/>
</label>
<button>
{isPending ? 'Pending' : 'Submit'}
</button>
{state.messages.length > 0 &&
state.messages.map((message, index) => {
return (
<p
key={index}
>
{message}
</p>
)
})}
</form>
</div>
)
}
The server action implementation is as follows:
export async function sendEmail(
prevState: { messages: string[] },
formData: FormData,
captchaToken: string
) {
// Implement necessary logic using the token and formData
return {
status: 'success',
messages: ['Thank you for contacting us!']
}
}
An issue arises with TypeScript in relation to handling formAction within the handleSubmit function. Specifically, the error message states: "Expected 0 arguments, but got 2".
To resolve this issue while still passing the captchaToken to the formAction function alongside the formData, how can I ensure that it is properly received by sendEmail?