diff --git a/packages/forms/src/components/Form.tsx b/packages/forms/src/components/Form.tsx index 37139cb0..2b1de013 100644 --- a/packages/forms/src/components/Form.tsx +++ b/packages/forms/src/components/Form.tsx @@ -123,8 +123,21 @@ export type FormRef = { export const FormContext = React.createContext(null); -export const useForm = () => { +const DEFAULT_CONTEXT_VALUE: FormContextValue = { + refs: [], + submitForm: () => Promise.resolve(), + focusField: () => {}, +}; + +export const useForm = ( + { suppressError }: { suppressError?: boolean } = { suppressError: false }, +) => { const context = React.useContext(FormContext); + + if (!context && suppressError) { + return DEFAULT_CONTEXT_VALUE; // return default values so internal useForm hooks don't throw undefined errors when user choose to suppress errors + } + if (!context) { __DEV__ && console.error( @@ -134,5 +147,6 @@ export const useForm = () => { 'useForm must be used within a FormContextProvider, please wrap your form field inside the
component', ); } + return context; }; diff --git a/packages/forms/src/hooks/useFormField.ts b/packages/forms/src/hooks/useFormField.ts index ff3b79b2..36a7c196 100644 --- a/packages/forms/src/hooks/useFormField.ts +++ b/packages/forms/src/hooks/useFormField.ts @@ -17,6 +17,7 @@ export type UseFormField = { hasValidation: boolean; hasError?: boolean; errorMessage?: string; + suppressError?: boolean; }; export const useFormField = ({ @@ -30,9 +31,10 @@ export const useFormField = ({ accessibilityHint, errorMessage, editable = true, + suppressError, style = {}, }: UseFormField) => { - const { refs, submitForm, focusField } = useForm(); + const { refs, submitForm, focusField } = useForm({ suppressError }); const fieldRef = React.useRef(ref); const checks = __DEV__ ? useChecks?.() : undefined;