Alan_szt
Alan_szt8mo ago

How to get access to the types generated by the server in the frontend (React)?

In this example, how do you replace data: any to the correct type?
import { trpc } from "../utils/trpc";

type Props = {
onSuccess: (data: any) => void;
};
export function CreateWorker(props: Props) {
const createWorkerMutation = trpc.createWorker.useMutation();

const handleCreateWorker = () => {
createWorkerMutation.mutate(
{ data: "hello" },
{
onSuccess: (data) => props.onSuccess(data),
}
);
};
return <button onClick={handleCreateWorker}>create</button>;
}
import { trpc } from "../utils/trpc";

type Props = {
onSuccess: (data: any) => void;
};
export function CreateWorker(props: Props) {
const createWorkerMutation = trpc.createWorker.useMutation();

const handleCreateWorker = () => {
createWorkerMutation.mutate(
{ data: "hello" },
{
onSuccess: (data) => props.onSuccess(data),
}
);
};
return <button onClick={handleCreateWorker}>create</button>;
}
2 Replies
Alan_szt
Alan_sztOP8mo ago
I found this. is it the good approach?
import type { AppRouter } from "../../../server";
import type { inferRouterOutputs } from "@trpc/server";

export type RouterOutputs = inferRouterOutputs<AppRouter>;

type Props = {
onSuccess: (data: RouterOutputs["createWorker"]) => void;
};
import type { AppRouter } from "../../../server";
import type { inferRouterOutputs } from "@trpc/server";

export type RouterOutputs = inferRouterOutputs<AppRouter>;

type Props = {
onSuccess: (data: RouterOutputs["createWorker"]) => void;
};
Alan_szt
Alan_sztOP4mo ago
Inferring Types | tRPC
It is often useful to access the types of your API within your clients. For this purpose, you are able to infer the types contained in your AppRouter.

Did you find this page helpful?