Skip to content

Commit 5d5ba10

Browse files
authored
Merge pull request #112 from workfloworchestrator/1904-prepolutate-array
1904: Prepopulate array items based on minItems
2 parents 2d44287 + 26d20fd commit 5d5ba10

File tree

1 file changed

+34
-4
lines changed

1 file changed

+34
-4
lines changed

frontend/packages/pydantic-forms/src/components/fields/ArrayField.tsx

Lines changed: 34 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import React from 'react';
1+
import React, { useEffect, useState } from 'react';
22
import { useFieldArray } from 'react-hook-form';
33

44
import { usePydanticFormContext } from '@/core';
@@ -10,13 +10,37 @@ import { RenderFields } from '../render';
1010

1111
export const ArrayField = ({ pydanticFormField }: PydanticFormElementProps) => {
1212
const { rhf, config } = usePydanticFormContext();
13+
const [isInitialized, setInitialized] = useState(false);
1314
const { control } = rhf;
1415
const { id: arrayName, arrayItem } = pydanticFormField;
1516
const { minItems, maxItems } = pydanticFormField.validations;
1617
const { fields, append, remove } = useFieldArray({
1718
control,
1819
name: arrayName,
1920
});
21+
22+
useEffect(() => {
23+
if (!isInitialized) {
24+
const arrayValueObject = {
25+
[arrayName]: arrayItem?.default,
26+
};
27+
const minItemCount = minItems || 1;
28+
const initialArray = Array.from(
29+
{ length: minItemCount },
30+
() => arrayValueObject,
31+
);
32+
append(initialArray);
33+
setInitialized(true);
34+
}
35+
}, [
36+
append,
37+
arrayItem?.default,
38+
arrayName,
39+
fields.length,
40+
isInitialized,
41+
minItems,
42+
]);
43+
2044
if (!arrayItem) return '';
2145

2246
const component = fieldToComponentMatcher(
@@ -25,7 +49,7 @@ export const ArrayField = ({ pydanticFormField }: PydanticFormElementProps) => {
2549
);
2650

2751
const renderField = (field: Record<'id', string>, index: number) => {
28-
const arrayField = itemizeArrayItem(index, arrayItem);
52+
const arrayItemField = itemizeArrayItem(index, arrayItem);
2953

3054
return (
3155
<div
@@ -41,13 +65,19 @@ export const ArrayField = ({ pydanticFormField }: PydanticFormElementProps) => {
4165
pydanticFormComponents={[
4266
{
4367
Element: component.Element,
44-
pydanticFormField: arrayField,
68+
pydanticFormField: arrayItemField,
4569
},
4670
]}
4771
extraTriggerFields={[arrayName]}
4872
/>
4973
{(!minItems || (minItems && fields.length > minItems)) && (
50-
<span onClick={() => remove(index)}>-</span>
74+
<span
75+
onClick={() => {
76+
remove(index);
77+
}}
78+
>
79+
-
80+
</span>
5181
)}
5282
</div>
5383
);

0 commit comments

Comments
 (0)