1
- import React from 'react' ;
1
+ import React , { useEffect , useState } from 'react' ;
2
2
import { useFieldArray } from 'react-hook-form' ;
3
3
4
4
import { usePydanticFormContext } from '@/core' ;
@@ -10,13 +10,37 @@ import { RenderFields } from '../render';
10
10
11
11
export const ArrayField = ( { pydanticFormField } : PydanticFormElementProps ) => {
12
12
const { rhf, config } = usePydanticFormContext ( ) ;
13
+ const [ isInitialized , setInitialized ] = useState ( false ) ;
13
14
const { control } = rhf ;
14
15
const { id : arrayName , arrayItem } = pydanticFormField ;
15
16
const { minItems, maxItems } = pydanticFormField . validations ;
16
17
const { fields, append, remove } = useFieldArray ( {
17
18
control,
18
19
name : arrayName ,
19
20
} ) ;
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
+
20
44
if ( ! arrayItem ) return '' ;
21
45
22
46
const component = fieldToComponentMatcher (
@@ -25,7 +49,7 @@ export const ArrayField = ({ pydanticFormField }: PydanticFormElementProps) => {
25
49
) ;
26
50
27
51
const renderField = ( field : Record < 'id' , string > , index : number ) => {
28
- const arrayField = itemizeArrayItem ( index , arrayItem ) ;
52
+ const arrayItemField = itemizeArrayItem ( index , arrayItem ) ;
29
53
30
54
return (
31
55
< div
@@ -41,13 +65,19 @@ export const ArrayField = ({ pydanticFormField }: PydanticFormElementProps) => {
41
65
pydanticFormComponents = { [
42
66
{
43
67
Element : component . Element ,
44
- pydanticFormField : arrayField ,
68
+ pydanticFormField : arrayItemField ,
45
69
} ,
46
70
] }
47
71
extraTriggerFields = { [ arrayName ] }
48
72
/>
49
73
{ ( ! minItems || ( minItems && fields . length > minItems ) ) && (
50
- < span onClick = { ( ) => remove ( index ) } > -</ span >
74
+ < span
75
+ onClick = { ( ) => {
76
+ remove ( index ) ;
77
+ } }
78
+ >
79
+ -
80
+ </ span >
51
81
) }
52
82
</ div >
53
83
) ;
0 commit comments