-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
FormConsumer.tsx
49 lines (46 loc) 路 1.26 KB
/
FormConsumer.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
import React, { useRef } from 'react'
import { isFn, deprecate } from '@uform/shared'
import { FormSpy } from './FormSpy'
import { IForm, LifeCycleTypes } from '@uform/core'
import { IFormConsumerProps, IFormConsumerAPI } from '../types'
const transformStatus = (type: string, ref: any) => {
switch (type) {
case LifeCycleTypes.ON_FORM_INIT:
return 'initialize'
case LifeCycleTypes.ON_FORM_SUBMIT_START:
ref.current.submitting = true
return 'submitting'
case LifeCycleTypes.ON_FORM_SUBMIT_END:
ref.current.submitting = false
return 'submitted'
default:
return ref.current.submitting ? 'submitting' : type
}
}
const transformFormAPI = (
api: IForm,
type: string,
ref: any
): IFormConsumerAPI => {
deprecate('FormConsumer', 'Please use FormSpy Component.')
return {
status: transformStatus(type, ref),
state: api.getFormState(),
submit: api.submit,
reset: api.reset
}
}
export const FormConsumer: React.FunctionComponent<
IFormConsumerProps
> = props => {
const ref = useRef({})
return (
<FormSpy {...props}>
{({ form, type }) => {
return isFn(props.children)
? props.children(transformFormAPI(form, type, ref))
: props.children
}}
</FormSpy>
)
}