Skip to content

Commit

Permalink
feat: escape provider requirement / suppress error (#212)
Browse files Browse the repository at this point in the history
* add default value to be used when suppressing error

* Add suppress error option to useForm hook

* add suppressError to useFormField
  • Loading branch information
JDMathew authored Jul 18, 2024
1 parent ba2095d commit 687d821
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
16 changes: 15 additions & 1 deletion packages/forms/src/components/Form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,21 @@ export type FormRef = {

export const FormContext = React.createContext<FormContextValue | null>(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(
Expand All @@ -134,5 +147,6 @@ export const useForm = () => {
'useForm must be used within a FormContextProvider, please wrap your form field inside the <Form /> component',
);
}

return context;
};
4 changes: 3 additions & 1 deletion packages/forms/src/hooks/useFormField.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export type UseFormField = {
hasValidation: boolean;
hasError?: boolean;
errorMessage?: string;
suppressError?: boolean;
};

export const useFormField = ({
Expand All @@ -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;
Expand Down

0 comments on commit 687d821

Please sign in to comment.