setValue() does not trigger a update to the watch when used in useFormContext
See original GitHub issueDescribe the bug
A clear and concise description of what the bug is.
I am currently trying to listen to changes watch and in the scenario where I use the useFormContext()
hook, the watch doesn’t update onChange. Avoiding the use of refs given I am currently hooked in materialUI
To Reproduce Steps to reproduce the behavior:
- Set up a function component with a useForm hook ’
- render a
<FormContext {...methods} >
- Create function component named ‘Input’ that is an input that is state controlled.
- In the above component hook up via the
useFormContext()
Example:
`import React, { useEffect } from “react”; import { Box, Typography, FormControl, TextField } from “@material-ui/core”; import { useFormContext } from “react-hook-form”;
type SomeFakeInputProps = { name: string; require?: boolean; fieldName: string; defaultValue: string; };
export const SomeFakeInput: React.FC<SomeFakeInputProps> = ({ fieldName, name }) => { const [value, setStateValue] = React.useState(“”); const { register, errors, formState, setValue } = useFormContext(); const fieldTouched = formState.touched.includes(fieldName); const error = errors[fieldName];
useEffect(() => {
register({ name: fieldName });
}, []);
function handleChange({ target }: React.ChangeEvent<HTMLInputElement>) {
setValue(fieldName, target.value);
setStateValue(target.value);
}
return (
<Box>
<FormControl disabled={formState.isSubmitting}>
<TextField aria-label={name} name={fieldName} onChange={handleChange} />
{fieldTouched && error && <Typography color="error"> {error} </Typography>}
</FormControl>
</Box>
);
};`
- Log out the watch from the origin
useForm()
hook and notice that watch state is not being updated on input change.
I will try to make a code sandbox to replicate this issue. Current don’t have the capacity to do so.
Issue Analytics
- State:
- Created 4 years ago
- Comments:6 (5 by maintainers)
Ahh awesome! Thanks for the quick response. I managed to build out a quick demo of the issue.
https://codesandbox.io/s/react-hook-form-setvalue-with-controlled-input-bug-fgeik
https://github.com/react-hook-form/react-hook-form/releases/tag/v3.23.10 published the fix thanks 😃 please star the repo to support if you find it useful.