In my schema, I have an id property. When I use useFieldArray, it automatically overrides that id.
I'm using shadcn-ui
react-hook-form: 7.45.0
const { fields, append, remove, update } = useFieldArray<{ id?: string, test?: number[] }>({
name: 'testArray',
control: form.control,
});
fields.map((item, index) => (
<div key={item.id}>
<FormField
name={`testArray.${index}.id`}
render={({ field }) => (
<FormItem>
<Select
onValueChange={field.onChange}
defaultValue={field.value}
>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select" />
</SelectTrigger>
</FormControl>
<SelectContent>
{
selects?.map((select) => (
<SelectItem value={select.id}>{select.name}</SelectItem>
))
}
</SelectContent>
</Select>
</FormItem>
)}
/>
{
item.test.map((value: number, index2: number) => (
<div>
<FormField
key={`${value}`}
name={`testArray.${index}.test.${index2}`}
render={({ field: testField }) => (
<FormItem className="w-full">
<FormControl>
<Slider onValueChange={(currentValue) => form.setValue(`testArray.${index}.test.${index2}`, currentValue[0])} value={[testField .value]} />
</FormControl>
</FormItem>
)}
/>
</div>
))
}
<Button onClick={() => update(index, { id: item.id, split: [...item.test, 0] })}>Add Number To Array</Button>
<Button onClick={() => remove(index)}>Remove</Button>
</div>
<Button
onClick={() => append({
id: '',
test: [100],
})}
>
Add List
</Button>
I've read that I could use keyName property which works fine, but docs says that its deprecated and id shouldn't be overridden in newer version, but it is.
I encountered the same. This library requires a 'unique' id prop to be able to add new entries. However, you can specify that keyName to be different. As you experienced, the default keyName is id. See example below:
// myItemsThatHaveId is of type { id: number; something: string; }[] in the state
const { fields, update } = useFieldArray({
control,
name: 'myItemsThatHaveId',
keyName: '_id'
});
// field will now have id: number; _id: string; something: string;
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