Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux - React Hook Form connectivity

I'm using react-hook-form v7 with redux-toolkit in my react project. I have multiple forms under FormContext. Is there any way to sync form's data with redux store synchronously? Actually, there is information about this in the official document, but I did not fully understand how redux connect works and what is meant by updateAction.

import { useForm } from "react-hook-form";
import { connect } from "react-redux";
import updateAction from "./actions";

export default function App(props) {
  const { register, handleSubmit, setValue } = useForm({
    defaultValues: {
      firstName: '',
      lastName: '',
    }
  });
  // Submit your data into Redux store
  const onSubmit = data => props.updateAction(data);
  
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register("firstName")} />
      <input {...register("lastName")} />
      <input type="submit" />
    </form>
  );
}

// Connect your component with redux
connect(({ firstName, lastName }) => ({ firstName, lastName }), updateAction)(YourForm);

The redux store should appear like this:

{
// other state values
lorem : {...},
ipsum : {...},
// form state values
form1: {
input1: ...,
...,
}
// OR
formContext: {
 form1: {..}
}
like image 843
maybe Avatar asked Oct 28 '25 03:10

maybe


1 Answers

There may be other ways of doing this but I used watch.

const { watch } = useForm({ mode: "all" }}

It's important to use a mode other than the default onSubmit on useForm if you want synchronous updates. I used mode: "all" which triggers updates on both blur and change events.


Create a redux slice using createSlice

export const formSlice = createSlice({
  name: "form",
  initialState: {
    firstName: "",
    lastName: "",
  },
  reducers: {
    updateForm(state, action) {
      return { ...state, ...action.payload };
    },
  },
});

export const { updateForm } = formSlice.actions;

export default formSlice.reducer;

Subscribe to watch and dispatch action updateForm

  useEffect(() => {
    const subscription = watch((value) => {
      dispatch(updateForm(value));
    });
    return () => subscription.unsubscribe();
  }, [dispatch, watch]);

codesandbox

like image 104
eleventhaus Avatar answered Oct 30 '25 16:10

eleventhaus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!