From 0cb833fbca63a64f2e360491b9d8a40ca8f66396 Mon Sep 17 00:00:00 2001 From: Nikhil Agarwal Date: Sat, 23 Jul 2022 21:42:39 +0530 Subject: [PATCH] Fix for insert in field array --- example/forms/SimpleFieldArray.tsx | 2 +- example/forms/components/Fields.tsx | 14 +++++++++++++- src/atoms.ts | 6 ++++-- 3 files changed, 18 insertions(+), 4 deletions(-) diff --git a/example/forms/SimpleFieldArray.tsx b/example/forms/SimpleFieldArray.tsx index be206d9..5f58dfb 100644 --- a/example/forms/SimpleFieldArray.tsx +++ b/example/forms/SimpleFieldArray.tsx @@ -52,7 +52,7 @@ function SimpleFieldArray(props) { Reset diff --git a/example/forms/components/Fields.tsx b/example/forms/components/Fields.tsx index 036ee95..ffa724d 100644 --- a/example/forms/components/Fields.tsx +++ b/example/forms/components/Fields.tsx @@ -100,7 +100,8 @@ export function TableField(props: TableFieldProps) { name: props.name, // If validate function is removed, only the particular field inside field array will render // For real-time validation, we need to listen to all fields inside the field array to pass data to validate function. - validate: (value) => (value?.length <=1 ? 'Need at least two rows' : undefined), + validate: (value) => + value?.length <= 1 ? 'Need at least two rows' : undefined, }); return ( @@ -129,6 +130,17 @@ export function TableField(props: TableFieldProps) { > Remove + diff --git a/src/atoms.ts b/src/atoms.ts index 5f5aeea..f4d59da 100644 --- a/src/atoms.ts +++ b/src/atoms.ts @@ -422,8 +422,10 @@ export function setFieldArrayDataAndExtraInfo( dataIdx < startIndex + dataArr.length; dataIdx++ ) { - const fieldValues = dataArr[dataIdx]; - const extraInfos = extraInfoArr?.[dataIdx]; + // Need to subtract startIndex because only the new data is passed during insert + // For e.g. if startIndex is 1 and data is at index 0, we need to get the value at index 0 for row index 1. + const fieldValues = dataArr[dataIdx - startIndex]; + const extraInfos = extraInfoArr?.[dataIdx - startIndex]; const rowId = rowIds[dataIdx]; const fieldAncestors = params.ancestors.length ? [...params.ancestors, { name: params.name, rowId }]