I am using react hook form to show data on a pop up. Click an item, it shows data about the item.
The problem, is I click item A, it shows data for item A, but I then click item B, it still shows data for the previous item A.
The below code gets the correct information for item B:
const { control, handleSubmit } = useForm<Item>({
defaultValues: {
name: Item.name,
description: Item.description,
},
});
However this controller still shows the data from item A:
<Controller
name="name"
control={control}
rules={{
required: true,
}}
render={({ field, fieldState: { error } }) => (
<TextField
{...field}
label="Name"
error={!!error}
helperText={!!error && 'Name is required.'}
/>
)}
/>
So defaultValues is getting updated correctly, but the controller is not. I have tried adding a watch, but it too shows the old value from item A.
The fix was to add a reset:
const { control, handleSubmit } = useForm<Item>({
defaultValues: {
name: Item.name,
description: Item.description,
},
});
useEffect(() => {
reset(item)
}, [item]);