1- import React from 'react' ;
1+ import React , { useEffect , useState } from 'react' ;
22import { useFieldArray } from 'react-hook-form' ;
33
44import { usePydanticFormContext } from '@/core' ;
@@ -10,13 +10,37 @@ import { RenderFields } from '../render';
1010
1111export 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