-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
Copy pathFormik.tsx
executable file
·999 lines (925 loc) · 29.8 KB
/
Formik.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
import * as React from 'react';
import isEqual from 'react-fast-compare';
import deepmerge from 'deepmerge';
import {
FormikConfig,
FormikErrors,
FormikState,
FormikTouched,
FormikValues,
FormikProps,
FieldMetaProps,
FieldInputProps,
} from './types';
import {
isFunction,
isString,
setIn,
isEmptyChildren,
isPromise,
setNestedObjectValues,
getActiveElement,
getIn,
} from './utils';
import { FormikProvider } from './FormikContext';
import invariant from 'tiny-warning';
import { LowPriority, unstable_runWithPriority } from 'scheduler';
// We already used FormikActions. So we'll go all Elm-y, and use Message.
type FormikMessage<Values> =
| { type: 'SUBMIT_ATTEMPT' }
| { type: 'SUBMIT_FAILURE' }
| { type: 'SUBMIT_SUCCESS' }
| { type: 'SET_ISVALIDATING'; payload: boolean }
| { type: 'SET_ISSUBMITTING'; payload: boolean }
| { type: 'SET_VALUES'; payload: Values }
| { type: 'SET_FIELD_VALUE'; payload: { field: string; value?: any } }
| { type: 'SET_FIELD_TOUCHED'; payload: { field: string; value?: boolean } }
| { type: 'SET_FIELD_ERROR'; payload: { field: string; value?: string } }
| { type: 'SET_TOUCHED'; payload: FormikTouched<Values> }
| { type: 'SET_ERRORS'; payload: FormikErrors<Values> }
| { type: 'SET_STATUS'; payload: any }
| { type: 'SET_FORMIK_STATE'; payload: FormikState<Values> }
| { type: 'RESET_FORM'; payload: FormikState<Values> };
// State reducer
function formikReducer<Values>(
state: FormikState<Values>,
msg: FormikMessage<Values>
) {
switch (msg.type) {
case 'SET_VALUES':
return { ...state, values: msg.payload };
case 'SET_TOUCHED':
return { ...state, touched: msg.payload };
case 'SET_ERRORS':
return { ...state, errors: msg.payload };
case 'SET_STATUS':
return { ...state, status: msg.payload };
case 'SET_ISSUBMITTING':
return { ...state, isSubmitting: msg.payload };
case 'SET_ISVALIDATING':
return { ...state, isValidating: msg.payload };
case 'SET_FIELD_VALUE':
return {
...state,
values: setIn(state.values, msg.payload.field, msg.payload.value),
};
case 'SET_FIELD_TOUCHED':
return {
...state,
touched: setIn(state.touched, msg.payload.field, msg.payload.value),
};
case 'SET_FIELD_ERROR':
return {
...state,
errors: setIn(state.errors, msg.payload.field, msg.payload.value),
};
case 'RESET_FORM':
case 'SET_FORMIK_STATE':
return { ...state, ...msg.payload };
case 'SUBMIT_ATTEMPT':
return {
...state,
touched: setNestedObjectValues<FormikTouched<Values>>(
state.values,
true
),
isSubmitting: true,
submitCount: state.submitCount + 1,
};
case 'SUBMIT_FAILURE':
return {
...state,
isSubmitting: false,
};
case 'SUBMIT_SUCCESS':
return {
...state,
isSubmitting: false,
};
default:
return state;
}
}
// Initial empty states // objects
const emptyErrors: FormikErrors<unknown> = {};
const emptyTouched: FormikTouched<unknown> = {};
// This is an object that contains a map of all registered fields
// and their validate functions
interface FieldRegistry {
[field: string]: {
validate: (value: any) => string | Promise<string> | undefined;
};
}
export function useFormik<Values extends FormikValues = FormikValues>({
validateOnChange = true,
validateOnBlur = true,
isInitialValid,
enableReinitialize = false,
onSubmit,
...rest
}: FormikConfig<Values>) {
const props = { validateOnChange, validateOnBlur, onSubmit, ...rest };
const initialValues = React.useRef(props.initialValues);
const initialErrors = React.useRef(props.initialErrors || emptyErrors);
const initialTouched = React.useRef(props.initialTouched || emptyTouched);
const initialStatus = React.useRef(props.initialStatus);
const isMounted = React.useRef<boolean>(false);
const fieldRegistry = React.useRef<FieldRegistry>({});
React.useEffect(() => {
if (__DEV__) {
invariant(
typeof isInitialValid === 'undefined',
'isInitialValid has been deprecated and will be removed in future versions of Formik. Please use initialErrors instead.'
);
}
}, [isInitialValid]);
React.useEffect(() => {
isMounted.current = true;
return () => {
isMounted.current = false;
};
}, []);
const [state, dispatch] = React.useReducer<
React.Reducer<FormikState<Values>, FormikMessage<Values>>
>(formikReducer, {
values: props.initialValues,
errors: props.initialErrors || emptyErrors,
touched: props.initialTouched || emptyTouched,
status: props.initialStatus,
isSubmitting: false,
isValidating: false,
submitCount: 0,
});
const runValidateHandler = React.useCallback(
(values: Values, field?: string): Promise<FormikErrors<Values>> => {
return new Promise((resolve, reject) => {
const maybePromisedErrors = (props.validate as any)(values, field);
if (maybePromisedErrors == null) {
// use loose null check here on purpose
resolve(emptyErrors);
} else if (isPromise(maybePromisedErrors)) {
(maybePromisedErrors as Promise<any>).then(
errors => {
resolve(errors || emptyErrors);
},
actualException => {
if (process.env.NODE_ENV !== 'production') {
console.warn(
`Warning: An unhandled error was caught during validation in <Formik validate />`,
actualException
);
}
reject(actualException);
}
);
} else {
resolve(maybePromisedErrors);
}
});
},
[props.validate]
);
/**
* Run validation against a Yup schema and optionally run a function if successful
*/
const runValidationSchema = React.useCallback(
(values: Values, field?: string): Promise<FormikErrors<Values>> => {
return new Promise((resolve, reject) => {
const validationSchema = props.validationSchema;
const schema = isFunction(validationSchema)
? validationSchema(field)
: validationSchema;
let promise =
field && schema.validateAt
? schema.validateAt(field, values)
: validateYupSchema(values, schema);
promise.then(
() => {
resolve(emptyErrors);
},
(err: any) => {
// Yup will throw a validation error if validation fails. We catch those and
// resolve them into Formik errors. We can sniff is something is a Yup error
// by checking error.name.
// @see https://github.com/jquense/yup#validationerrorerrors-string--arraystring-value-any-path-string
if (err.name === 'ValidationError') {
resolve(yupToFormErrors(err));
} else {
// We throw any other errors
if (process.env.NODE_ENV !== 'production') {
console.warn(
`Warning: An unhandled error was caught during validation in <Formik validationSchema />`,
err
);
}
reject(err);
}
}
);
});
},
[props.validationSchema]
);
const runSingleFieldLevelValidation = React.useCallback(
(field: string, value: void | string): Promise<string> => {
return new Promise(resolve =>
resolve(fieldRegistry.current[field].validate(value))
);
},
[]
);
const runFieldLevelValidations = React.useCallback(
(values: Values): Promise<FormikErrors<Values>> => {
const fieldKeysWithValidation: string[] = Object.keys(
fieldRegistry.current
).filter(f => isFunction(fieldRegistry.current[f].validate));
// Construct an array with all of the field validation functions
const fieldValidations: Promise<string>[] =
fieldKeysWithValidation.length > 0
? fieldKeysWithValidation.map(f =>
runSingleFieldLevelValidation(f, getIn(values, f))
)
: [Promise.resolve('DO_NOT_DELETE_YOU_WILL_BE_FIRED')]; // use special case ;)
return Promise.all(fieldValidations).then((fieldErrorsList: string[]) =>
fieldErrorsList.reduce((prev, curr, index) => {
if (curr === 'DO_NOT_DELETE_YOU_WILL_BE_FIRED') {
return prev;
}
if (curr) {
prev = setIn(prev, fieldKeysWithValidation[index], curr);
}
return prev;
}, {})
);
},
[runSingleFieldLevelValidation]
);
// Run all validations and return the result
const runAllValidations = React.useCallback(
(values: Values) => {
return Promise.all([
runFieldLevelValidations(values),
props.validationSchema ? runValidationSchema(values) : {},
props.validate ? runValidateHandler(values) : {},
]).then(([fieldErrors, schemaErrors, validateErrors]) => {
const combinedErrors = deepmerge.all<FormikErrors<Values>>(
[fieldErrors, schemaErrors, validateErrors],
{ arrayMerge }
);
return combinedErrors;
});
},
[
props.validate,
props.validationSchema,
runFieldLevelValidations,
runValidateHandler,
runValidationSchema,
]
);
// Run validations and dispatching the result as low-priority via rAF.
//
// The thinking is that validation as a result of onChange and onBlur
// should never block user input. Note: This method should never be called
// during the submission phase because validation prior to submission
// is actaully high-priority since we absolutely need to guarantee the
// form is valid before executing props.onSubmit.
const validateFormWithLowPriority = useEventCallback(
(values: Values = state.values) => {
return unstable_runWithPriority(LowPriority, () => {
return runAllValidations(values).then(combinedErrors => {
if (!!isMounted.current) {
dispatch({ type: 'SET_ERRORS', payload: combinedErrors });
}
return combinedErrors;
});
});
},
[runAllValidations, state.values]
);
// Run all validations methods and update state accordingly
const validateFormWithHighPriority = useEventCallback(
(values: Values = state.values) => {
dispatch({ type: 'SET_ISVALIDATING', payload: true });
return runAllValidations(values).then(combinedErrors => {
if (!!isMounted.current) {
dispatch({ type: 'SET_ISVALIDATING', payload: false });
if (!isEqual(state.errors, combinedErrors)) {
dispatch({ type: 'SET_ERRORS', payload: combinedErrors });
}
}
return combinedErrors;
});
},
[state.values, state.errors, runAllValidations]
);
const resetForm = React.useCallback(
(nextState?: Partial<FormikState<Values>>) => {
const values =
nextState && nextState.values
? nextState.values
: initialValues.current;
const errors =
nextState && nextState.errors
? nextState.errors
: initialErrors.current
? initialErrors.current
: props.initialErrors || {};
const touched =
nextState && nextState.touched
? nextState.touched
: initialTouched.current
? initialTouched.current
: props.initialTouched || {};
const status =
nextState && nextState.status
? nextState.status
: initialStatus.current
? initialStatus.current
: props.initialStatus;
initialValues.current = values;
initialErrors.current = errors;
initialTouched.current = touched;
initialStatus.current = status;
dispatch({
type: 'RESET_FORM',
payload: {
isSubmitting: !!nextState && !!nextState.isSubmitting,
errors,
touched,
status,
values,
isValidating: !!nextState && !!nextState.isValidating,
submitCount:
!!nextState &&
!!nextState.submitCount &&
typeof nextState.submitCount === 'number'
? nextState.submitCount
: 0,
},
});
},
[props.initialErrors, props.initialStatus, props.initialTouched]
);
React.useEffect(() => {
if (
enableReinitialize &&
isMounted.current === true &&
!isEqual(initialValues.current, props.initialValues)
) {
initialValues.current = props.initialValues;
resetForm();
}
}, [enableReinitialize, props.initialValues, resetForm]);
const validateField = useEventCallback(
(name: string) => {
// This will efficiently validate a single field by avoiding state
// changes if the validation function is synchronous. It's different from
// what is called when using validateForm.
if (isFunction(fieldRegistry.current[name].validate)) {
const value = getIn(state.values, name);
const maybePromise = fieldRegistry.current[name].validate(value);
if (isPromise(maybePromise)) {
// Only flip isValidating if the function is async.
dispatch({ type: 'SET_ISVALIDATING', payload: true });
return maybePromise
.then((x: any) => x)
.then((error: string) => {
dispatch({
type: 'SET_FIELD_ERROR',
payload: { field: name, value: error },
});
dispatch({ type: 'SET_ISVALIDATING', payload: false });
});
} else {
dispatch({
type: 'SET_FIELD_ERROR',
payload: {
field: name,
value: maybePromise as string | undefined,
},
});
return Promise.resolve(maybePromise as string | undefined);
}
} else {
return Promise.resolve();
}
},
[state.values]
);
const registerField = React.useCallback((name: string, { validate }: any) => {
fieldRegistry.current[name] = {
validate,
};
}, []);
const unregisterField = React.useCallback((name: string) => {
delete fieldRegistry.current[name];
}, []);
const setTouched = useEventCallback(
(touched: FormikTouched<Values>) => {
dispatch({ type: 'SET_TOUCHED', payload: touched });
return validateOnBlur
? validateFormWithLowPriority(state.values)
: Promise.resolve();
},
[validateFormWithLowPriority, state.values, validateOnBlur]
);
const setErrors = React.useCallback((errors: FormikErrors<Values>) => {
dispatch({ type: 'SET_ERRORS', payload: errors });
}, []);
const setValues = useEventCallback(
(values: Values) => {
dispatch({ type: 'SET_VALUES', payload: values });
return validateOnChange
? validateFormWithLowPriority(state.values)
: Promise.resolve();
},
[validateFormWithLowPriority, state.values, validateOnChange]
);
const setFieldError = React.useCallback(
(field: string, value: string | undefined) => {
dispatch({
type: 'SET_FIELD_ERROR',
payload: { field, value },
});
},
[]
);
const setFieldValue = useEventCallback(
(field: string, value: any, shouldValidate: boolean = true) => {
dispatch({
type: 'SET_FIELD_VALUE',
payload: {
field,
value,
},
});
return validateOnChange && shouldValidate
? validateFormWithLowPriority(setIn(state.values, field, value))
: Promise.resolve();
},
[validateFormWithLowPriority, state.values, validateOnChange]
);
const executeChange = React.useCallback(
(eventOrTextValue: string | React.ChangeEvent<any>, maybePath?: string) => {
// By default, assume that the first argument is a string. This allows us to use
// handleChange with React Native and React Native Web's onChangeText prop which
// provides just the value of the input.
let field = maybePath;
let val = eventOrTextValue;
let parsed;
// If the first argument is not a string though, it has to be a synthetic React Event (or a fake one),
// so we handle like we would a normal HTML change event.
if (!isString(eventOrTextValue)) {
// If we can, persist the event
// @see https://reactjs.org/docs/events.html#event-pooling
if ((eventOrTextValue as React.ChangeEvent<any>).persist) {
(eventOrTextValue as React.ChangeEvent<any>).persist();
}
const {
type,
name,
id,
value,
checked,
outerHTML,
options,
multiple,
} = (eventOrTextValue as React.ChangeEvent<any>).target;
field = maybePath ? maybePath : name ? name : id;
if (!field && __DEV__) {
warnAboutMissingIdentifier({
htmlContent: outerHTML,
documentationAnchorLink: 'handlechange-e-reactchangeeventany--void',
handlerName: 'handleChange',
});
}
val = /number|range/.test(type)
? ((parsed = parseFloat(value)), isNaN(parsed) ? '' : parsed)
: /checkbox/.test(type) // checkboxes
? getValueForCheckbox(getIn(state.values, field!), checked, value)
: !!multiple // <select multiple>
? getSelectedValues(options)
: value;
}
if (field) {
// Set form fields by name
setFieldValue(field, val);
}
},
[setFieldValue, state.values]
);
const handleChange = React.useCallback(
(
eventOrPath: string | React.ChangeEvent<any>
): void | ((eventOrTextValue: string | React.ChangeEvent<any>) => void) => {
if (isString(eventOrPath)) {
return event => executeChange(event, eventOrPath);
} else {
executeChange(eventOrPath);
}
},
[executeChange]
);
const setFieldTouched = useEventCallback(
(
field: string,
touched: boolean = true,
shouldValidate: boolean = true
) => {
dispatch({
type: 'SET_FIELD_TOUCHED',
payload: {
field,
value: touched,
},
});
return validateOnBlur && shouldValidate
? validateFormWithLowPriority(state.values)
: Promise.resolve();
},
[validateFormWithLowPriority, state.values, validateOnBlur]
);
const executeBlur = React.useCallback(
(e: any, path?: string) => {
if (e.persist) {
e.persist();
}
const { name, id, outerHTML } = e.target;
const field = path ? path : name ? name : id;
if (!field && __DEV__) {
warnAboutMissingIdentifier({
htmlContent: outerHTML,
documentationAnchorLink: 'handleblur-e-any--void',
handlerName: 'handleBlur',
});
}
setFieldTouched(field, true);
},
[setFieldTouched]
);
const handleBlur = React.useCallback(
(eventOrString: any): void | ((e: any) => void) => {
if (isString(eventOrString)) {
return event => executeBlur(event, eventOrString);
} else {
executeBlur(eventOrString);
}
},
[executeBlur]
);
function setFormikState(
stateOrCb:
| FormikState<Values>
| ((state: FormikState<Values>) => FormikState<Values>)
): void {
if (isFunction(stateOrCb)) {
dispatch({ type: 'SET_FORMIK_STATE', payload: stateOrCb(state) });
} else {
dispatch({ type: 'SET_FORMIK_STATE', payload: stateOrCb });
}
}
const setStatus = React.useCallback((status: any) => {
dispatch({ type: 'SET_STATUS', payload: status });
}, []);
const setSubmitting = React.useCallback((isSubmitting: boolean) => {
dispatch({ type: 'SET_ISSUBMITTING', payload: isSubmitting });
}, []);
const imperativeMethods = {
resetForm,
validateForm: validateFormWithHighPriority,
validateField,
setErrors,
setFieldError,
setFieldTouched,
setFieldValue,
setStatus,
setSubmitting,
setTouched,
setValues,
setFormikState,
};
const executeSubmit = useEventCallback(() => {
return onSubmit(state.values, imperativeMethods);
}, [imperativeMethods, onSubmit, state.values]);
const submitForm = useEventCallback(() => {
dispatch({ type: 'SUBMIT_ATTEMPT' });
return validateFormWithHighPriority().then(
(combinedErrors: FormikErrors<Values>) => {
const isActuallyValid = Object.keys(combinedErrors).length === 0;
if (isActuallyValid) {
return Promise.resolve(executeSubmit())
.then(() => {
if (!!isMounted.current) {
dispatch({ type: 'SUBMIT_SUCCESS' });
}
})
.catch(_errors => {
if (!!isMounted.current) {
dispatch({ type: 'SUBMIT_FAILURE' });
throw _errors;
}
});
} else if (!!isMounted.current) {
// ^^^ Make sure Formik is still mounted before calling setState
dispatch({ type: 'SUBMIT_FAILURE' });
return;
}
return;
}
);
}, [executeSubmit, validateFormWithHighPriority]);
const handleSubmit = useEventCallback(
(e?: React.FormEvent<HTMLFormElement>) => {
if (e && e.preventDefault && isFunction(e.preventDefault)) {
e.preventDefault();
}
if (e && e.stopPropagation && isFunction(e.stopPropagation)) {
e.stopPropagation();
}
// Warn if form submission is triggered by a <button> without a
// specified `type` attribute during development. This mitigates
// a common gotcha in forms with both reset and submit buttons,
// where the dev forgets to add type="button" to the reset button.
if (__DEV__ && typeof document !== 'undefined') {
// Safely get the active element (works with IE)
const activeElement = getActiveElement();
if (
activeElement !== null &&
activeElement instanceof HTMLButtonElement
) {
invariant(
activeElement.attributes &&
activeElement.attributes.getNamedItem('type'),
'You submitted a Formik form using a button with an unspecified `type` attribute. Most browsers default button elements to `type="submit"`. If this is not a submit button, please add `type="button"`.'
);
}
}
submitForm();
},
[submitForm]
);
const handleReset = useEventCallback(
e => {
if (e && e.preventDefault && isFunction(e.preventDefault)) {
e.preventDefault();
}
if (e && e.stopPropagation && isFunction(e.stopPropagation)) {
e.stopPropagation();
}
if (props.onReset) {
const maybePromisedOnReset = (props.onReset as any)(
state.values,
imperativeMethods
);
if (isPromise(maybePromisedOnReset)) {
(maybePromisedOnReset as Promise<any>).then(resetForm);
} else {
resetForm();
}
} else {
resetForm();
}
},
[imperativeMethods, props.onReset, resetForm, state.values]
);
const getFieldMeta = React.useCallback(
(name: string) => {
return {
value: getIn(state.values, name),
error: getIn(state.errors, name),
touched: !!getIn(state.touched, name),
initialValue: getIn(initialValues.current, name),
initialTouched: !!getIn(initialTouched.current, name),
initialError: getIn(initialErrors.current, name),
};
},
[state.errors, state.touched, state.values]
);
const getFieldProps = React.useCallback(
({
name,
type,
value: valueProp, // value is special for checkboxes
as: is,
multiple,
}): [FieldInputProps<any>, FieldMetaProps<any>] => {
const valueState = getIn(state.values, name);
const field: FieldInputProps<any> = {
name,
value: valueState,
onChange: handleChange,
onBlur: handleBlur,
};
if (type === 'checkbox') {
if (valueProp === undefined) {
field.checked = !!valueState;
} else {
field.checked = !!(
Array.isArray(valueState) && ~valueState.indexOf(valueProp)
);
field.value = valueProp;
}
} else if (type === 'radio') {
field.checked = valueState === valueProp;
field.value = valueProp;
} else if (is === 'select' && multiple) {
field.value = field.value || [];
field.multiple = true;
}
return [field, getFieldMeta(name)];
},
[getFieldMeta, handleBlur, handleChange, state.values]
);
const dirty = React.useMemo(
() => !isEqual(initialValues.current, state.values),
[state.values]
);
const isValid = React.useMemo(
() =>
typeof isInitialValid !== 'undefined'
? dirty
? state.errors && Object.keys(state.errors).length === 0
: isInitialValid !== false && isFunction(isInitialValid)
? (isInitialValid as (props: FormikConfig<Values>) => boolean)(props)
: (isInitialValid as boolean)
: state.errors && Object.keys(state.errors).length === 0,
[isInitialValid, dirty, state.errors, props]
);
const ctx = {
...state,
initialValues: initialValues.current,
initialErrors: initialErrors.current,
initialTouched: initialTouched.current,
initialStatus: initialStatus.current,
handleBlur,
handleChange,
handleReset,
handleSubmit,
resetForm,
setErrors,
setFormikState,
setFieldTouched,
setFieldValue,
setFieldError,
setStatus,
setSubmitting,
setTouched,
setValues,
submitForm,
validateForm: validateFormWithHighPriority,
validateField,
isValid,
dirty,
unregisterField,
registerField,
getFieldProps,
validateOnBlur,
validateOnChange,
};
return ctx;
}
export function Formik<
Values extends FormikValues = FormikValues,
ExtraProps = {}
>(props: FormikConfig<Values> & ExtraProps) {
const formikbag = useFormik<Values>(props);
const { component, children, render } = props;
return (
<FormikProvider value={formikbag}>
{component
? React.createElement(component as any, formikbag)
: render
? render(formikbag)
: children // children come last, always called
? isFunction(children)
? (children as ((bag: FormikProps<Values>) => React.ReactNode))(
formikbag as FormikProps<Values>
)
: !isEmptyChildren(children)
? React.Children.only(children)
: null
: null}
</FormikProvider>
);
}
function warnAboutMissingIdentifier({
htmlContent,
documentationAnchorLink,
handlerName,
}: {
htmlContent: string;
documentationAnchorLink: string;
handlerName: string;
}) {
console.warn(
`Warning: Formik called \`${handlerName}\`, but you forgot to pass an \`id\` or \`name\` attribute to your input:
${htmlContent}
Formik cannot determine which value to update. For more info see https://github.com/jaredpalmer/formik#${documentationAnchorLink}
`
);
}
/**
* Transform Yup ValidationError to a more usable object
*/
export function yupToFormErrors<Values>(yupError: any): FormikErrors<Values> {
let errors: FormikErrors<Values> = {};
if (yupError.inner.length === 0) {
return setIn(errors, yupError.path, yupError.message);
}
for (let err of yupError.inner) {
if (!(errors as any)[err.path]) {
errors = setIn(errors, err.path, err.message);
}
}
return errors;
}
/**
* Validate a yup schema.
*/
export function validateYupSchema<T extends FormikValues>(
values: T,
schema: any,
sync: boolean = false,
context: any = {}
): Promise<Partial<T>> {
let validateData: FormikValues = {};
for (let k in values) {
if (values.hasOwnProperty(k)) {
const key = String(k);
validateData[key] = values[key] !== '' ? values[key] : undefined;
}
}
return schema[sync ? 'validateSync' : 'validate'](validateData, {
abortEarly: false,
context: context,
});
}
/**
* deepmerge array merging algorithm
* https://github.com/KyleAMathews/deepmerge#combine-array
*/
function arrayMerge(target: any[], source: any[], options: any): any[] {
const destination = target.slice();
source.forEach(function(e: any, i: number) {
if (typeof destination[i] === 'undefined') {
const cloneRequested = options.clone !== false;
const shouldClone = cloneRequested && options.isMergeableObject(e);
destination[i] = shouldClone
? deepmerge(Array.isArray(e) ? [] : {}, e, options)
: e;
} else if (options.isMergeableObject(e)) {
destination[i] = deepmerge(target[i], e, options);
} else if (target.indexOf(e) === -1) {
destination.push(e);
}
});
return destination;
}
/** Return multi select values based on an array of options */
function getSelectedValues(options: any[]) {
return options.filter(el => el.selected).map(el => el.value);
}
/** Return the next value for a checkbox */
function getValueForCheckbox(
currentValue: string | any[],
checked: boolean,
valueProp: any
) {
// eslint-disable-next-line eqeqeq
if (valueProp == 'true' || valueProp == 'false') {
return !!checked;
}
if (checked) {
return Array.isArray(currentValue)
? currentValue.concat(valueProp)
: [valueProp];
}
if (!Array.isArray(currentValue)) {
return !!currentValue;
}
const index = currentValue.indexOf(valueProp);
if (index < 0) {
return currentValue;
}
return currentValue.slice(0, index).concat(currentValue.slice(index + 1));
}
function useEventCallback<T extends (...args: any[]) => any>(
fn: T,
dependencies: React.DependencyList
): T {
const ref: any = React.useRef(() => {
throw new Error('Cannot call an event handler while rendering.');
});
React.useEffect(() => {
ref.current = fn;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [fn, ...dependencies]);
return React.useCallback<any>(
(...argz: any[]) => {
const fn = ref.current;
return fn(...argz);
},
[ref]
) as T;
}