| 40 | * ``` |
| 41 | */ |
| 42 | export function useFormState< |
| 43 | TFieldValues extends FieldValues = FieldValues, |
| 44 | TTransformedValues = TFieldValues, |
| 45 | >( |
| 46 | props?: UseFormStateProps<TFieldValues, TTransformedValues>, |
| 47 | ): UseFormStateReturn<TFieldValues> { |
| 48 | const formControl = useFormControlContext< |
| 49 | TFieldValues, |
| 50 | any, |
| 51 | TTransformedValues |
| 52 | >(); |
| 53 | const { control = formControl, disabled, name, exact } = props || {}; |
| 54 | const [formState, updateFormState] = React.useState(control._formState); |
| 55 | const _localProxyFormState = React.useRef({ |
| 56 | isDirty: false, |
| 57 | isLoading: false, |
| 58 | dirtyFields: false, |
| 59 | touchedFields: false, |
| 60 | validatingFields: false, |
| 61 | isValidating: false, |
| 62 | isValid: false, |
| 63 | errors: false, |
| 64 | }); |
| 65 | |
| 66 | useIsomorphicLayoutEffect( |
| 67 | () => |
| 68 | control._subscribe({ |
| 69 | name, |
| 70 | formState: _localProxyFormState.current, |
| 71 | exact, |
| 72 | callback: (formState) => { |
| 73 | !disabled && |
| 74 | updateFormState({ |
| 75 | ...control._formState, |
| 76 | ...formState, |
| 77 | }); |
| 78 | }, |
| 79 | }), |
| 80 | [name, disabled, exact], |
| 81 | ); |
| 82 | |
| 83 | React.useEffect(() => { |
| 84 | _localProxyFormState.current.isValid && control._setValid(true); |
| 85 | }, [control]); |
| 86 | |
| 87 | return React.useMemo( |
| 88 | () => |
| 89 | getProxyFormState( |
| 90 | formState, |
| 91 | control, |
| 92 | _localProxyFormState.current, |
| 93 | false, |
| 94 | ), |
| 95 | [formState, control], |
| 96 | ); |
| 97 | } |