A Simple tRPC Example
This example with display the current time on the server and it will update every minute by re-calling the server.
Loading...
The client code uses the React 'useEffect' hook with a interval call to 'refetch' tRPC function:
"use client";
import { useEffect } from "react";
import { useSession } from "next-auth/react";
import { trpc } from "@/utils/trpc/trpcNext";

export function TrpcSimpleDemo() {
const { data: session } = useSession();
const result = trpc.greet.useQuery(session?.user?.name ?? "User");

useEffect(() => {
const interval = setInterval(() => {
result.refetch();
}, 60000);
return () => clearInterval(interval);
}, []);

return (
<>
{result.isLoading ? (
<>Loading...</>
) : result.isSuccess ? (
<>{result.data}</>
) : (
<>Error!</>
)}
</>
);
}

export default trpc.withTRPC(TrpcSimpleDemo);
The server is setup as:
export const appRouter = router({
greet: publicProcedure.input(z.string()).query(async (opts) => {
const { input } = opts;
const dateWithoutSecond = new Date();
const time = dateWithoutSecond.toLocaleTimeString("en-GB", {
hour: "2-digit",
minute: "2-digit",
});
const greeting = "Hello " + input + " @ " + time;
return greeting;
}),
...
});
It's probably overkill to call the server for the current time, but this is a nice simple demonstrates of how tRPC works. We have not included all the setup, some more boiler plate is not shown here.
const result = trpc.greet.useQuery(session?.user?.name ?? "User");
What is really interesting is that after the 'trpc', in this code, the types will auto complete to match those of the server (in this case 'greet' in the router definition code) as the developer types.
As you can probably imagine, adding more server types and consuming them from the client after this setup would be straight forward and extremely efficient.

FUTORO