1

I'm using react hook form, and I'm looking for a way to inject custom props to the handleSubmit method returned by the hook. The reason I need to do this is my component acts as a Consumer for a state library, and I want to update the state after submitting the form. I may also want to pass props to the method.

From looking at the API, it seems like this isn't possible. Any thoughts on a workaround or how to do this?

Jay K.
  • 546
  • 2
  • 10
  • 17

2 Answers2

2

I don't use this library, but it seems that getValues function returned from useForm hook opens the way to synchronize Your component state with form data stored in the "react-hook-form":

docs

import React, { useMemo, useEffect, useState } from "react";
import { useForm } from "react-hook-form";

export default function App() {
  const { register, getValues } = useForm();
  const [ valuesState, setValuesState ] = useState();

  const values = useMemo(() => getValues());

  useEffect(() => setValuesState(values), [values]);

  return (
    <form>
      [...]
    </form>
  );
}
1

why not just update the state during handleSubmit?

export default function App() {
  const { register, getValues } = useForm();
  const onSubmit = data => {
    // do your state update here update(data)
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      [...]
    </form>
  );
}
Bill
  • 17,872
  • 19
  • 83
  • 131
  • Unfortunately, in my situation, I had no access to state from the body of the function, only from the `return (...)` block. I was using https://github.com/jamiebuilds/unstated. But @Mateusz proposed a good solution imo. – Jay K. Jan 12 '20 at 00:51