on 91176c2 help sign in
bridge/src/form/BridgeForm.js
54 lines 1.4 kB history raw
1import React, { useCallback } from 'react';
2import { Form } from 'react-final-form';
3import setFieldData from 'final-form-set-field-data';
4import arrayMutators from 'final-form-arrays';
5import { noop } from 'lodash';
7import ValuesHandler from './ValuesHandler';
8import ValidationPauser from './ValidationPauser';
9import WarningEngine from './WarningEngine';
11/**
12 * BridgeForm adds nice-to-haves for every form in bridge.
13 * + afterSubmit callback for redirects
14 * + default onSubmit to noop so react-final-form doesn't throw
15 * + pauses validation when the form is unmounted
16 * + `onValues` handler for reactive changes
17 * + automatically includes array and field data mutators
18 */
19export default function BridgeForm({
20 children,
21 onValues,
22 onSubmit = noop,
23 afterSubmit = noop,
24 warnings,
25 ...rest
26}) {
27 const _onSubmit = useCallback(
28 async (...args) => {
29 const errors = await onSubmit(...args);
30 if (errors) {
31 return errors;
32 }
34 afterSubmit();
35 },
36 [afterSubmit, onSubmit]
37 );
39 return (
40 <Form
41 mutators={{ setFieldData, ...arrayMutators }}
42 onSubmit={_onSubmit}
43 {...rest}>
44 {formProps => (
45 <>
46 {warnings && <WarningEngine warnings={warnings} />}
47 <ValidationPauser />
48 {children(formProps)}
49 {onValues && <ValuesHandler onValues={onValues} />}
50 </>
51 )}
52 </Form>
53 );