Reputation: 135
I am searching for help regarding a problem with react-hook-form / useFieldArray.
I have an Array like this:
[
{name: "one", data: "long string"},
{name: "two", data: "another long string"},
]
This Array is within a form and rendered with the help of useFieldArray
.
Now I want to set a new data
on the first element. The documentation of react-hook-form gives the function "update":
As I dont want to trigger a remount I am using the setValue API like this:
form.setValue("array.0.data", newValue);
When I do so, I get the new value by using the functions form.watch
and form.getValues
, but when I query the fields value by using array.fields[0].data
I still get the old value.
I would appreciate any help on how to update a single value in an array and get the new value as well in the field as in the form without getting a remount.
Best Regards, Tobias
Upvotes: 5
Views: 11650
Reputation: 101
first will be the example and then the explanation.
the method to do the change:
const setSkuDescription = (
value: string,
index: number,
field: FieldArrayWithId<Fields, 'product', 'id'>
): void => {
update(index, {
...field, // all the info in the current object field this is required and not partial (they say is in the doc)
productID: value, // one of the fields i want to update
skuDescriptions: rawProducts // another field i want to update
.map((p) => {
if (p.ta_name === value) return p;
})
.filter((p) => p !== undefined) as Product[]
});
};
where im using the method:
<CFormSelect
// this is for reference to you to see where to use the method
onChange={(d) => setSkuDescription(d.currentTarget.value, index, field)
}>
<option hidden>---</option>
{products.map((product, key) => (
<option value={product.value as string} key={key}>
{product.label}
</option>
))}
</CFormSelect>
where the change is reflected
<CFormSelect
{...register("product.${index}.description", { // this is for reference to you to see where the method will render in the HTML if you need it
required: "The field SKU Description is required"
})}>
<option hidden>---</option>
{field.skuDescriptions.map((p, key) => (
<option value={p.ta_productid as string} key={key}>
{p.ta_size}
</option>
))}
</CFormSelect>
exaplanation: first the method that receives 3 parameters. the "value" that you want to modify, the second is the index of the array that the array gives you when mapping it and finally it is the entire field object that returns the mapping of the array since this is required to be used to update all the information of the object ( this part is referring to the official documentation).
required information in the docs
Upvotes: 1