issue: Removing from a field array does not unregister the field value correctly if the useForm's defaultValues has been set with a value
Version Number
7.51.1
Codesandbox/Expo snack
https://codesandbox.io/p/devbox/react-hook-form-usefieldarray-yprzdc
Steps to reproduce
- Click on the "Remove last" button twice.
- Click on the "Append" button twice.
- Check out the form values returned by
watch()in the black box. The newly added values should have been all 10, however it still shows up as 20 for the 2nd element and 30 for the 3rd element.
Expected behaviour
After removing then appending to the field array, the newly appended element should have a value of 10 as what was passed into the append() function. The fields returned by the useFieldArray hook does seem to display the correct value at first, but then it gets overridden when the field array updates.
What browsers are you seeing the problem on?
Edge, Chrome
Relevant log output
No response
Code of Conduct
- [x] I agree to follow this project's Code of Conduct
broken csb link
broken csb link
My bad, forgot to update the perms. Should be good now!
thanks will check it out later.
can you clean up your codesandbox, ideally just use native input to reproduce the issue. also the demo works as expect as well.
I've updated the CodeSandbox to use the native inputs instead.
As for the demo, what I meant was the value being returned from the watch() function doesn't seem to be correct. After removing 2 elements, and then appending back another 2 elements, the values on these 2 new elements should have been what was passed into the append() function, which is an object { select: 10 }. However, watch() shows that the new values are still 20 for the 2nd element, and 30 for the 3rd element, which is what was passed into useForm()'s defaultValues.
import { useForm, useFieldArray, FormProvider } from "react-hook-form";
function App() {
const { control, watch } = useForm({
defaultValues: {
textField: "",
selectionArray: [{ select: '10' }, { select: '20' }, { select: '30' }],
},
});
const { fields, append, remove } = useFieldArray({
name: "selectionArray",
shouldUnregister: true,
control,
});
console.log(fields);
console.log('watch', watch())
const appendHandler = () => {
append({ select: '10' });
};
const removeHandler = () => {
const lastFieldIndex = fields.length - 1;
remove(lastFieldIndex);
};
return (
<form>
<button type={"button"} onClick={appendHandler}>Append</button>
<button type={"button"} onClick={removeHandler}>Remove last</button>
<div>
{fields.map((field, index) => (
<input
key={field.id}
name={`selectionArray.${index}.select`}
defaultValue={field.select}
/>
))}
</div>
</form>
);
}
export default App;
working version, useFieldArary doesn't work with useForm shouldUnregister as it would conflict when input get unmountd.
@bluebill1049 That works, thanks. Just wondering though, what happens if I need both the shouldUnregister on the form level and on the array field level?