reduce redundant trpc error handling code to function
This commit is contained in:
parent
ee7268e724
commit
8b42377453
@ -13,6 +13,7 @@ import { useRouter } from "next/router";
|
||||
import { HeaderFooterLayout } from "~/layouts/HeaderFooterLayout";
|
||||
import { QueryWaitWrapper } from "~/components/LoadingWrapper";
|
||||
import { type AuditoryResource } from "@prisma/client";
|
||||
import { parseTRPCErrorMessage } from "~/utils/parseTRPCError";
|
||||
|
||||
const EditResourcePage = () => {
|
||||
const router = useRouter();
|
||||
@ -50,18 +51,7 @@ const EditResourcePage = () => {
|
||||
await router.push(`/resources/${data.id}`);
|
||||
},
|
||||
onError: (error) => {
|
||||
try {
|
||||
const zodErrors = JSON.parse(error.message) as unknown as { message: string }[];
|
||||
setServerError(
|
||||
zodErrors
|
||||
.map((error) => {
|
||||
return error.message;
|
||||
})
|
||||
.join(", ")
|
||||
);
|
||||
} catch {
|
||||
setServerError(error.message);
|
||||
}
|
||||
setServerError(parseTRPCErrorMessage(error.message));
|
||||
},
|
||||
});
|
||||
|
||||
|
@ -15,6 +15,7 @@ import {
|
||||
} from "~/components/admin/resources/form";
|
||||
import { HeaderFooterLayout } from "~/layouts/HeaderFooterLayout";
|
||||
import { api } from "~/utils/api";
|
||||
import { parseTRPCErrorMessage } from "~/utils/parseTRPCError";
|
||||
|
||||
const EditResourcePage = () => {
|
||||
const router = useRouter();
|
||||
@ -31,6 +32,9 @@ const EditResourcePage = () => {
|
||||
setServerError(undefined);
|
||||
await router.push(`/resources/${resData.id}`);
|
||||
},
|
||||
onError: (error) => {
|
||||
setServerError(parseTRPCErrorMessage(error.message));
|
||||
},
|
||||
});
|
||||
|
||||
const onSubmit: SubmitHandler<ResourceCreateInput> = (data) => {
|
||||
@ -61,7 +65,9 @@ const EditResourcePage = () => {
|
||||
>
|
||||
<div className="mb-12">
|
||||
<ResourceForm
|
||||
methods={formMethods as UseFormReturn<ResourceUpdateInput>}
|
||||
methods={
|
||||
formMethods as unknown as UseFormReturn<ResourceUpdateInput>
|
||||
}
|
||||
error={serverError}
|
||||
/>
|
||||
</div>
|
||||
|
@ -17,7 +17,7 @@ const emptyStringToUndefined = (val: string | undefined | null) => {
|
||||
};
|
||||
|
||||
const AuditoryResourceSchema = z.object({
|
||||
icon: z.string().min(1).optional(),
|
||||
icon: z.string().min(1).optional().nullable(),
|
||||
name: z.string().min(1),
|
||||
description: z.string().min(1),
|
||||
manufacturer: z.object({
|
||||
|
12
src/utils/parseTRPCError.ts
Normal file
12
src/utils/parseTRPCError.ts
Normal file
@ -0,0 +1,12 @@
|
||||
export const parseTRPCErrorMessage = (message: string) => {
|
||||
try {
|
||||
const zodErrors = JSON.parse(message) as unknown as { message: string }[];
|
||||
return zodErrors
|
||||
.map((error) => {
|
||||
return error.message;
|
||||
})
|
||||
.join(", ");
|
||||
} catch {
|
||||
return message;
|
||||
}
|
||||
};
|
Loading…
x
Reference in New Issue
Block a user