Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: escape provider requirement / suppress error #212

Merged
merged 3 commits into from
Jul 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading