Jay K.
Jay K.

Reputation: 636

Way to inject custom props/methods to `handleSubmit`?

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?

Upvotes: 1

Views: 1138

Answers (2)

Bill
Bill

Reputation: 19318

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>
  );
}

Upvotes: 1

Mateusz Falkowski
Mateusz Falkowski

Reputation: 436

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>
  );
}

Upvotes: 2

Related Questions