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: {..}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With