(name: string, config: UseFieldConfig = {})
| 28 | value === "" ? undefined : value; |
| 29 | |
| 30 | function useField< |
| 31 | FieldValue = any, |
| 32 | T extends HTMLElement = HTMLElement, |
| 33 | FormValues = Record<string, any>, |
| 34 | >(name: string, config: UseFieldConfig = {}): FieldRenderProps<FieldValue, T> { |
| 35 | const { |
| 36 | afterSubmit, |
| 37 | allowNull, |
| 38 | component, |
| 39 | data, |
| 40 | defaultValue, |
| 41 | format = defaultFormat, |
| 42 | formatOnBlur, |
| 43 | initialValue, |
| 44 | multiple, |
| 45 | parse = defaultParse, |
| 46 | subscription = all, |
| 47 | type, |
| 48 | validateFields, |
| 49 | value: _value, |
| 50 | } = config; |
| 51 | const form: FormApi<FormValues> = useForm<FormValues>("useField"); |
| 52 | |
| 53 | const configRef = useLatest(config); |
| 54 | |
| 55 | const register = ( |
| 56 | callback: (state: FieldState<any>) => void, |
| 57 | silent: boolean, |
| 58 | ) => |
| 59 | // avoid using `state` const in any closures created inside `register` |
| 60 | // because they would refer `state` from current execution context |
| 61 | // whereas actual `state` would defined in the subsequent `useField` hook |
| 62 | // execution |
| 63 | // (that would be caused by `setState` call performed in `register` callback) |
| 64 | form.registerField(name as keyof FormValues, callback, subscription, { |
| 65 | afterSubmit, |
| 66 | beforeSubmit: () => { |
| 67 | const { |
| 68 | beforeSubmit, |
| 69 | formatOnBlur, |
| 70 | format = defaultFormat, |
| 71 | } = configRef.current; |
| 72 | |
| 73 | if (formatOnBlur) { |
| 74 | const fieldState = form.getFieldState(name as keyof FormValues); |
| 75 | if (fieldState) { |
| 76 | const { value } = fieldState; |
| 77 | const formatted = format(value, name); |
| 78 | |
| 79 | if (formatted !== value) { |
| 80 | form.change(name as keyof FormValues, formatted); |
| 81 | } |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | return beforeSubmit && beforeSubmit(); |
| 86 | }, |
| 87 | data, |
searching dependent graphs…