Like the title states - how can I correctly define and type custom params in addition to the native event object in my async onSubmitHandler for a form.
This currently works, but is having only the native event as a single parameter:
const onSubmitHandler: FormEventHandler<HTMLFormElement> = async (event) => {
event.preventDefault()
const res = await signIn('credentials', {
email: userInfo.email,
password: userInfo.password,
redirect: false,
})
console.log('res', res)
}
I have tried doing it like so but the following code results in two errors:
interface SubmitHandlerInterface {
event: FormEventHandler<HTMLFormElement>
customStrParam: string
customNumParam: number
}
const onSubmitHandler = async ({event, customStrParam, customNumParam}:SubmitHandlerInterface) => {
event.preventDefault()
const res = await signIn('credentials', {
email: userInfo.email,
password: userInfo.password,
redirect: false,
})
console.log('res', res)
}
Error 1 - event.preventDefault() warns that
Property 'preventDefault' does not exist on type 'FormEventHandler'.ts(2339)
Error 2 - lower in the render function where I reference the onSubmitHandler in a form like so <form onSubmit={onSubmitHandler}>
I get this warning:
Type '({ event, customStrParam, customNumParam }: SubmitHandlerInterface) => Promise' is not assignable to type 'FormEventHandler'. Types of parameters '__0' and 'event' are incompatible. Type 'FormEvent' is missing the following properties from type 'SubmitHandlerInterface': event, customStrParam, customNumParamts(2322) index.d.ts(1409, 9): The expected type comes from property 'onSubmit' which is declared here on type 'DetailedHTMLProps<FormHTMLAttributes, HTMLFormElement>'
How should I be typing in this scenario? Thank you.
CodePudding user response:
I'm not sure if you can extend the default onSubmit directly, but here's my solution.
You are on the right track with the second example. But you are probably using it wrong in the form element. Here's my example that works.
You are getting Error 1 because you are using wrong event type. You should be using : React.FormEvent<HTMLFormElement>
Interface and handler:
interface SubmitHandlerInterface {
event: React.FormEvent<HTMLFormElement>
customStrParam: string
customNumParam: number
}
const customSubmitHandler = async ({
event,
customStrParam,
customNumParam,
}: SubmitHandlerInterface): Promise<void> => {
console.log({ event, customStrParam, customNumParam })
}
Usage:
<form
onSubmit={async (event): Promise<void> => {
await customSubmitHandler({
event,
customStrParam: 'My string',
customNumParam: 100,
})
}}
></form>