Im using React Hook Form with redux.
In a component, I first have to perform an action that sends a request to the backend and assigns the result in Redux.
So in the component I don't have the value of the form at the beginning. Only when the data has been assigned in the Redux.
How can I now fill the fields with the values from the Redux?
export default function Foo() {
const { baz } = useSelector(state => state.bar)
useEffect(() => {
dispatch(fetchBaz())
}
const { handleSubmit, register, errors, reset, watch, setError } = useForm({
validationSchema,
defaultValues: baz
})
return (
<input
key="someKey"
name={bazBaz}
ref={register}
onChange={handleChange}
/>
)
}
The problem is that when rendering for the first time, baz is not yet available and the defaultValues only set {}.
I found thisAsync request with hook form, but baz is not yet set in the promise and therefore I cannot do a reset(baz)
there.
How do I set the fields in the form with existing values?
Resetting the form when you get new data inside a useEffect will do the Job. The code below is not tested, but you should get the idea.
export default function Foo() {
const { baz } = useSelector(state => state.bar)
const { handleSubmit, register, errors, reset, watch, setError } = useForm({
defaultValues: baz
})
useEffect(() => {
dispatch(fetchBaz())
}, [])
useEffect(() => {
if(baz) reset(baz)
}, [baz])
return (
<input
name={'baz'}
ref={register({})}
/>
)
}
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