tRPC mutation onError handler error type for shared logic

I have two mutations on my frontend that should handle the response in the same way. So I extract the onError function so these two mutations can re-use the logic but I have a problem on how to type the error so the in function handling is pleased with typescript and the onError handler is also pleased.
// What type of the error should be here?
const onApiError = (error: ???) => {...}


const createMutation = api.location.create.useMutation({ onError: onApiError });
const editMutation = api.location.edit.useMutation({ onError: onApiError });
// What type of the error should be here?
const onApiError = (error: ???) => {...}


const createMutation = api.location.create.useMutation({ onError: onApiError });
const editMutation = api.location.edit.useMutation({ onError: onApiError });
I have tried like error: TRPCClientError<AppRouter> this does satisfy the function and internal of it but doesn't comply with the onError handlers onError: onApiError
2 Replies
Neto
Neto3mo ago
the onError should have an type already
import type { TRPCClientErrorLike } from "@trpc/client";
import { TRPCError } from "@trpc/server";
import type { AppRouter } from "~/server/api/root";
import { api } from "~/trpc/react";

const defaultErrorHandler = (error: TRPCClientErrorLike<AppRouter>) => {
if (error instanceof TRPCError) {
// handle trpc errors
}
};

export default function SomePage() {
const createMutation = api.post.create.useMutation({
onError: defaultErrorHandler,
});
}
import type { TRPCClientErrorLike } from "@trpc/client";
import { TRPCError } from "@trpc/server";
import type { AppRouter } from "~/server/api/root";
import { api } from "~/trpc/react";

const defaultErrorHandler = (error: TRPCClientErrorLike<AppRouter>) => {
if (error instanceof TRPCError) {
// handle trpc errors
}
};

export default function SomePage() {
const createMutation = api.post.create.useMutation({
onError: defaultErrorHandler,
});
}
Mugetsu
MugetsuOP3mo ago
Thanks ! Yeah i needed to assert the error type inside the handler and make error param of unknow type
Want results from more Discord servers?
Add your server