'React Typescript onSubmit type
I'm having issues around creating an onSubmit function and giving it a type.
On the very first line where you'd normally set a type for the function, no matter what I seem to give even any or unknown I'm seeing an error.
The error suggests I can't put type of any on the type of
(event: FormEvent<HTMLFormElement>, data: FormProps) => void
But even if I do give it this exact suggested type I still return an error.
const onSubmitHandler = (
e: SyntheticEvent<HTMLFormElement>,
setVerificationId: Dispatch<SetStateAction<string>>,
setVerificationToken: Dispatch<SetStateAction<VerificationStatus>>): TRYING_TO_RESOLVE_WHAT_THIS_TYPE_IS => {
e.preventDefault()
setUserData({
platform: '',
name: {
givenNames: givenNames ? givenNames : memberDetails.memberNameDetails.givenNames,
surname: surname ? surname : memberDetails.memberNameDetails.lastName
},
email: email,
dob: formattedDateOfBirth,
currentAddress: {
line1: streetNameInformation,
postCode: postCode,
suburb: suburb,
state: state,
country: country,
}})
aService.postVerificationRegister(userData)
.then(response => {
setVerificationId(response.verificationId)
setVerificationToken(response.verificationToken)
})
.catch((e) => console.error("There was an error getting a verification token", e))
}
<form id="not-the-form" role="form" action="/" onSubmit={onSubmitHandler}>
Solution 1:[1]
This should be a SyntheticEvent
Solution 2:[2]
I just pulled the semantic-ui-react library and tested. The following works with typescript (assuming you're using the 2nd argument).
import React from "react";
import { Form, FormProps } from "semantic-ui-react";
const Component = () => {
const handleSubmit = (e: React.FormEvent<HTMLFormElement>, data: FormProps) => {/* your code */};
return (
<Form onSubmit={handleSubmit} />
);
};
If you're not using the data argument then you'd have
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => { /* your code */};
The return type that you're thinking typescript is complaining about is automatically determined to be "void" by typescript because the function is not returning any value.
Edit: Your question appears to have changed, and your handler now has 3 arguments. Neither the html <form/> element or the semantic-ui-react <Form/> onSubmit function signatures match what you're passing. It sounds like you're wanting to pass custom arguments to your handler. In which case you'd need to have a higher order function.
const onSubmitHandler = (setVerificationId: type, setVerificationToken: type) = (e: React.FormEvent<HTMLFormElement>) => { /* your code */}
// calling code
<Form onSubmit={onSubmitHandler(setVerificationId, setVerificationToken)}>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dharman |
| Solution 2 |
