skip to Main Content

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:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. 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


  1. 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.

    Login or Signup to reply.
  2. Do not call hooks in event handlers.

    const handleSubmit = (values) => {
      const { status, data } = usePostRequest("/api/holidays-request", {
        dateFrom: "2023-02-01",
        dateTo: "2023-02-28",
        fromHalf: 0,
        toHalf: 0,
      });
    };
    

    See Invalid Hook Call Warning for details.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search