Replies: 3 comments
-
|
This is by design. Two workarounds depending on what you need: 1. Keep handleSubmit((data) => {
const payload = { ...data, listField: data.listField.length ? data.listField : null };
submit(payload);
});2. Skip The issue you linked confirms this is a known limitation with no plans to change it. |
Beta Was this translation helpful? Give feedback.
-
|
Yes, that is correct: If your initial state or Recommended Solution: Boundary MappingThe idiomatic way to handle this is to avoid passing
Here is an example: import { DefaultValues, useFieldArray, useForm } from "react-hook-form";
type Values = { listField: { a: string }[] }; // Keep array non-nullable in form types
// 1. Map null from API to [] for default values
const apiResponse = { listField: null };
const defaultValues: DefaultValues<Values> = {
listField: apiResponse.listField ?? []
};
export default function Test() {
const form = useForm<Values>({ defaultValues });
useFieldArray({ control: form.control, name: "listField" });
const onSubmit = (data: Values) => {
// 2. Map empty array back to null before sending to backend
const payload = {
...data,
listField: data.listField.length === 0 ? null : data.listField
};
console.log("Payload to API:", payload);
};
return (
<form onSubmit={form.handleSubmit(onSubmit)}>
{/* ... */}
<button type="submit">Submit</button>
</form>
);
} |
Beta Was this translation helpful? Give feedback.
-
|
There's a new |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Example type and default values:
When trying to use this with
useFieldArray, the value in the form state immediately becomes an empty array. This leads to the form being marked as dirty, which is not good for our use case.Question: Is there a way to handle nullable arrays without the form spuriously being marked as dirty, or do we have to make sure our model does not include nullable arrays?
I haven't been able to find much about this in docs etc, the clearest answer I've seen is in this discussion.
Below is a full reproduction, where we see that
values.listFieldanddefaultValues.listFieldare immediately different. If we remove the line withuseFieldArraythey are both null.Beta Was this translation helpful? Give feedback.
All reactions