@@ -9,6 +9,7 @@ import React, {
99 createContext ,
1010 useCallback ,
1111 useEffect ,
12+ useMemo ,
1213 useRef ,
1314 useState ,
1415} from 'react' ;
@@ -173,10 +174,24 @@ function PydanticFormContextProvider({
173174 componentMatcher ,
174175 ) ;
175176
177+ const initialData = useMemo (
178+ ( ) =>
179+ getFormValuesFromFieldOrLabels (
180+ pydanticFormSchema ,
181+ {
182+ ...formLabels ?. data ,
183+ ...customData ,
184+ } ,
185+ componentMatcher ,
186+ ) ,
187+ [ componentMatcher , customData , formLabels ?. data , pydanticFormSchema ] ,
188+ ) ;
189+
176190 // initialize the react-hook-form
177191 const rhf = useForm ( {
178192 resolver : zodResolver ( resolver ) ,
179193 mode : 'all' ,
194+ values : initialData ,
180195 } ) ;
181196
182197 // Adds watch subscripton on form values
@@ -221,8 +236,15 @@ function PydanticFormContextProvider({
221236 }
222237
223238 setFormInputHistory ( new Map < string , object > ( ) ) ;
224- rhf . reset ( ) ;
225- } , [ apiResponse , isFullFilled , onSuccess , rhf , skipSuccessNotice ] ) ;
239+ rhf . reset ( initialData ) ;
240+ } , [
241+ apiResponse ,
242+ initialData ,
243+ isFullFilled ,
244+ onSuccess ,
245+ rhf ,
246+ skipSuccessNotice ,
247+ ] ) ;
226248
227249 // a useeffect for whenever the error response updates
228250 // sometimes we need to update the form,
@@ -255,26 +277,16 @@ function PydanticFormContextProvider({
255277 return ;
256278 }
257279
258- const initialData = getFormValuesFromFieldOrLabels (
259- pydanticFormSchema ,
260- {
261- ...formLabels ?. data ,
262- ...customData ,
263- } ,
264- componentMatcher ,
265- ) ;
266-
267- rhf . reset ( initialData ) ;
268- } , [ customData , formLabels , pydanticFormSchema , rhf , componentMatcher ] ) ;
280+ rhf . reset ( undefined , { keepDefaultValues : true } ) ;
281+ } , [ pydanticFormSchema , rhf ] ) ;
269282
270283 // a useeffect for filling data whenever formdefinition or labels update
271284 useEffect ( ( ) => {
272- // this makes sure default values are set.
273- resetFormData ( ) ;
274285 getHashForArray ( formInputData ) . then ( ( hash ) => {
275286 const currentStepFromHistory = formInputHistory . get ( hash ) ;
276287
277288 if ( currentStepFromHistory ) {
289+ rhf . reset ( ) ;
278290 Object . entries ( currentStepFromHistory ) . forEach (
279291 ( [ fieldName , fieldValue ] ) =>
280292 rhf . setValue ( fieldName , fieldValue , {
@@ -304,7 +316,6 @@ function PydanticFormContextProvider({
304316 const submitFormFn = useCallback ( ( ) => {
305317 setIsSending ( true ) ;
306318 addFormInputData ( rhf ?. getValues ( ) , ! ! errorDetails ) ;
307-
308319 window . scrollTo ( 0 , 0 ) ;
309320 } , [ rhf , errorDetails , addFormInputData ] ) ;
310321
0 commit comments