Skip to content
Closed
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
5 changes: 5 additions & 0 deletions frontend/.changeset/floppy-eels-invent.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'pydantic-forms': patch
---

Improves handling 500 api errors
35 changes: 31 additions & 4 deletions frontend/apps/example/src/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,42 @@ export default function Home() {
}) => {
const url = 'http://localhost:8000/form';

const fetchResult = await fetch(url, {
return fetch(url, {
method: 'POST',
body: JSON.stringify(requestBody),
headers: {
'Content-Type': 'application/json',
},
});
const jsonResult = await fetchResult.json();
return jsonResult;
})
.then(async (fetchResult) => {
// Note: https://chatgpt.com/share/68c16538-5544-800c-9684-1e641168dbff
if (
fetchResult.status === 400 ||
fetchResult.status === 510 ||
fetchResult.status === 200
) {
const data = await fetchResult.json();

return new Promise<Record<string, unknown>>((resolve) => {
if (fetchResult.status === 510) {
resolve({ ...data, status: 510 });
}
if (fetchResult.status === 400) {
resolve({ ...data, status: 400 });
}
if (fetchResult.status === 200) {
resolve({ ...data, status: 200 });
}
});
}
throw new Error(
`Status not 400, 510 or 200: ${fetchResult.statusText}`,
);
}) //
.catch((error) => {
// Note: https://chatgpt.com/share/68c16538-5544-800c-9684-1e641168dbff
throw new Error(`Fetch error: ${error}`);
});
};

const pydanticLabelProvider: PydanticFormLabelProvider = async () => {
Expand Down
8 changes: 4 additions & 4 deletions frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,12 @@ interface FieldWrapProps {
}

export const FieldWrap = ({ pydanticFormField, children }: FieldWrapProps) => {
const { errorDetails, reactHookForm, config } = usePydanticFormContext();
const { validationErrorDetails, reactHookForm, config } =
usePydanticFormContext();
const RowRenderer = config?.rowRenderer ? config.rowRenderer : FormRow;
const fieldState = reactHookForm.getFieldState(pydanticFormField.id);
const errorMsg =
errorDetails?.mapped?.[pydanticFormField.id]?.msg ??
validationErrorDetails?.mapped?.[pydanticFormField.id]?.msg ??
fieldState.error?.message;
const isInvalid = errorMsg ?? fieldState.invalid;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
*/
import React from 'react';

import RenderFormErrors from '@/components/render/RenderFormErrors';
import { RenderValidationErrors } from '@/components/render/RenderValidationErrors';
import { usePydanticFormContext } from '@/core';

const Header = () => {
Expand All @@ -17,7 +17,7 @@ const Header = () => {
{title ?? pydanticFormSchema?.title}
</h2>

<RenderFormErrors />
<RenderValidationErrors />
</>
);
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,13 @@ import { PydanticFormComponents, PydanticFormContextProps } from '@/types';

const RenderForm = (contextProps: PydanticFormContextProps) => {
const {
submitForm,
handleSubmit,
pydanticFormSchema,
config,
isLoading,
isFullFilled,
isSending,
apiError,
} = contextProps;

const { formRenderer, footerRenderer, headerRenderer } = config || {};
Expand All @@ -39,6 +40,12 @@ const RenderForm = (contextProps: PydanticFormContextProps) => {
<div>{t('loading')}</div>
);

const ErrorComponent = config.loadingComponent ?? <div>{t('error')}</div>;

if (apiError) {
return ErrorComponent;
}

if (isLoading && !isSending) {
return LoadingComponent;
}
Expand All @@ -56,7 +63,7 @@ const RenderForm = (contextProps: PydanticFormContextProps) => {
const HeaderRenderer = headerRenderer ?? Header;

return (
<form action={''} onSubmit={submitForm}>
<form action={''} onSubmit={handleSubmit}>
<HeaderRenderer />
<FormRenderer pydanticFormComponents={pydanticFormComponents} />
<FooterRenderer />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,15 @@ import React from 'react';
import { usePydanticFormContext } from '@/core';
import { getFieldLabelById } from '@/core/helper';

export default function RenderFormErrors() {
const { errorDetails, pydanticFormSchema } = usePydanticFormContext();
export function RenderValidationErrors() {
const { validationErrorDetails, pydanticFormSchema } =
usePydanticFormContext();

if (!errorDetails) {
if (!validationErrorDetails) {
return <></>;
}

const errors = errorDetails.source;
const errors = validationErrorDetails.source;
const rootError = errors
.filter((err) => err.loc.includes('__root__'))
.shift();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export * from './RenderFields';
export * from './RenderForm';
export * from './RenderFormErrors';
export * from './RenderValidationErrors';
export * from './RenderReactHookFormErrors';
export * from './RenderFields';
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@
import { zodResolver } from '@hookform/resolvers/zod';

import {
getErrorDetailsFromResponse,
getFormValuesFromFieldOrLabels,
getValidationErrorDetailsFromResponse,
} from '@/core/helper';
import {
useApiProvider,
Expand All @@ -33,6 +33,7 @@
} from '@/core/hooks';
import {
Locale,
PydanticFormApiResponseType,
PydanticFormContextProps,
PydanticFormFieldType,
PydanticFormSchemaRawJson,
Expand Down Expand Up @@ -88,7 +89,7 @@
[],
);

const [errorDetails, setErrorDetails] =
const [validationErrorDetails, setValidationErrorDetails] =
useState<PydanticFormValidationErrorDetails>();

const [isFullFilled, setIsFullFilled] = useState(false);
Expand All @@ -105,11 +106,11 @@
customDataProvider,
);

// fetch API response with form definition
// fetch API response with form definition, validation errors or success
const {
data: apiResponse,
isLoading: isLoadingSchema,
error,
error: apiError,
} = useApiProvider(formKey, formInputData, apiProvider);

const emptyRawSchema: PydanticFormSchemaRawJson = useMemo(
Expand Down Expand Up @@ -195,24 +196,24 @@
awaitReset();
return [...currentFormInputData, { ...reactHookFormValues }];
});
}, []);

Check warning on line 199 in frontend/packages/pydantic-forms/src/core/PydanticFormContextProvider.tsx

View workflow job for this annotation

GitHub Actions / linting-and-prettier

React Hook useCallback has missing dependencies: 'awaitReset', 'reactHookForm', and 'updateHistory'. Either include them or remove the dependency array

const submitFormFn = useCallback(() => {
const onSubmit = useCallback(() => {
setIsSending(true);
setErrorDetails(undefined);
setValidationErrorDetails(undefined);
addFormInputData();
window.scrollTo(0, 0);
}, []);

Check warning on line 206 in frontend/packages/pydantic-forms/src/core/PydanticFormContextProvider.tsx

View workflow job for this annotation

GitHub Actions / linting-and-prettier

React Hook useCallback has a missing dependency: 'addFormInputData'. Either include it or remove the dependency array

const onClientSideError = useCallback(
(data?: FieldValues) => {
// TODO implement save with errors toggle
if (data) {
reactHookForm.clearErrors();
submitFormFn();
onSubmit();
}
},
[reactHookForm, submitFormFn],
[reactHookForm, onSubmit],
);

const goToPreviousStep = () => {
Expand All @@ -225,15 +226,15 @@
});
};

const submitForm = reactHookForm.handleSubmit(
submitFormFn,
const handleSubmit = reactHookForm.handleSubmit(
onSubmit,
onClientSideError,
);

const resetForm = useCallback(
(e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
e.preventDefault();
setErrorDetails(undefined);
setValidationErrorDetails(undefined);
awaitReset();
reactHookForm.trigger();
},
Expand Down Expand Up @@ -285,7 +286,7 @@
const PydanticFormContextState = {
config,
customDataProvider,
errorDetails,
validationErrorDetails,
fieldDataStorage,
formInputData,
formKey,
Expand All @@ -299,8 +300,9 @@
pydanticFormSchema,
reactHookForm,
resetForm,
submitForm,
handleSubmit,
title,
apiError,
};

// useEffect to handle API responses
Expand All @@ -323,7 +325,9 @@
return;
}

if (apiResponse?.validation_errors) {
if (
apiResponse.type === PydanticFormApiResponseType.VALIDATION_ERRORS
) {
// Restore the data we got the error with and remove it from
// formInputData so we can add it again
setFormInputData((currentData) => {
Expand All @@ -333,16 +337,21 @@
return nextData;
});

setErrorDetails(getErrorDetailsFromResponse(apiResponse));
setValidationErrorDetails(
getValidationErrorDetailsFromResponse(apiResponse),
);
return;
}

if (apiResponse?.success) {
if (apiResponse.type === PydanticFormApiResponseType.SUCCESS) {
setIsFullFilled(true);
return;
}

if (apiResponse?.form && rawSchema !== apiResponse.form) {
if (
apiResponse.type === PydanticFormApiResponseType.FORM_DEFINITION &&
rawSchema !== apiResponse.form
) {
setRawSchema(apiResponse.form);
if (apiResponse.meta) {
setHasNext(!!apiResponse.meta.hasNext);
Expand All @@ -359,7 +368,7 @@
if (formKey !== formRef.current) {
setFormInputData([]);
setFormInputHistory(new Map<string, object>());
setErrorDetails(undefined);
setValidationErrorDetails(undefined);
formRef.current = formKey;
}
}, [formKey]);
Expand All @@ -379,20 +388,6 @@
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isFullFilled]); // Avoid completing the dependencies array here to avoid unwanted resetFormData calls

// useEffect to handles errors throws by the useApiProvider call
// for instance unexpected 500 errors
useEffect(() => {
if (!error) {
return;
}

setErrorDetails({
detail: 'Something unexpected went wrong',
source: [],
mapped: {},
});
}, [error]);

// useEffect to handle locale change
useEffect(() => {
const getLocale = () => {
Expand Down
Loading