Skip to content

Commit

Permalink
Fix for insert in field array
Browse files Browse the repository at this point in the history
  • Loading branch information
nikhilag committed Jul 23, 2022
1 parent 2284ec9 commit 0cb833f
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 4 deletions.
2 changes: 1 addition & 1 deletion example/forms/SimpleFieldArray.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ function SimpleFieldArray(props) {
Reset
</button>
<button type="button" onClick={() => validateFields([{name: 'items', type: 'field-array'}])}>
Validate Field Array
Validate
</button>
</div>
</form>
Expand Down
14 changes: 13 additions & 1 deletion example/forms/components/Fields.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -129,6 +130,17 @@ export function TableField(props: TableFieldProps) {
>
Remove
</button>
<button
type="button"
onClick={() =>
tableField.insert(
idx + 1,
tableField.getFieldArrayValue()[idx]
)
}
>
Duplicate Row
</button>
</td>
</React.Fragment>
</tr>
Expand Down
6 changes: 4 additions & 2 deletions src/atoms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }]
Expand Down

0 comments on commit 0cb833f

Please sign in to comment.