I am building a React Native app that uses Formik. When I submit the form I call handleSubmit
<Formik
onSubmit={values => {
handleSubmit(values)
}}>
I define this before the return
on my form:
const handleSubmit = (values) => {
const { status, data } = usePostRequest("/api/holidays-request", {
dateFrom: "2023-02-01",
dateTo: "2023-02-28",
fromHalf: 0,
toHalf: 0,
});
};
I have hard coded some values here for testing.
My usePostRequest
is a custom hook I wrote to actually send the data to my API.
When I submit my form then handleSubmit
is triggered but I get an erorr:
Warning: An unhandled error was caught from submitForm() [Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
- You might have mismatching versions of React and the renderer (such as React DOM)
- You might be breaking the Rules of Hooks
- You might have more than one copy of React in the same app
It must be reason 2 that I am failing but I am unsure how to use my usePostRequest
to submit the values from the form.
2
Answers
I would recommend you take a look at the custom hooks documentation
In this particular case you should write the post logic as a function and use it here directly.
Do not call hooks in event handlers.
See Invalid Hook Call Warning for details.