I’m getting an infinite loop when trying to update the total inside a table that uses the useFieldArray hook from react hook form.
const items = useWatch({
control,
name: "items",
});
const { fields, ...fieldsProps } = useFieldArray({
control: control,
name: "items",
});
const controlledFields = fields.map((field, index) => {
return {
...field,
...items[index],
};
});
I have an itemTable component where I pass the props:
<ItemTable
form={form}
control={control}
controlledFields={controlledFields}
data={items}
fieldsProps={fieldsProps}
isTaxInclusive={tax_inclusive}
isDiscountItemLevel={is_discount_item_level}
/>
Inside the ItemTable component i have a renderItemRow function where the infinite loop occurs:
function renderItemRow(item, key) {
const quantity = item.quantity;
const discountPercentage = item.discount_percentage || 0;
const discountAmount = item.discount_amount || 0;
const price = item.unit_price || 0;
// Calculate total discount
const discountTotal =
discountAmount > 0
? discountAmount * quantity
: (discountPercentage / 100) * price * quantity;
const itemTotal = quantity * price - discountTotal;
update(key, { // <-- infinite loop
total: itemTotal,
});
my goal is to display and update the correct item total whenever the user changes the quantity, price or tax percentage of a certain item:
<td id="total" className={`${styles.rowItem} w-[115px] px-2 font-bold`}>
<FormField
control={control}
name={`items[${key}].total`}
render={({ field }) => (
<FormItem>
<FormControl>
<Input
readOnly
variant="ghost"
className="text-right text-black"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>