shared useTRPCClient hook conversion to v11
In our mono repo, we have 30 or so MFEs which all use the same TRPC client setup. So, we abstracted the inner workings of getting the TRPC client set up away in a different package as a hook. Now, I'm converting the code to v11, and I'm running into deprecation warnings and typescript errors. Our hook looks like this:
Issue 1: TRPCClient type is no longer exported from @trpc/client. I assume we can replace it with
import { useState } from 'react';
import { createWSClient, getFetch, httpLink, splitLink, wsLink } from '@trpc/client';
import type { TRPCClient, TRPCLink } from '@trpc/client'; // [1] TRPCClient no longer exported
import type { AnyRouter } from '@trpc/server'; // [2] AnyRouter deprecated
type TRPC<TRouter extends AnyRouter> = {
createClient: (opts: { links: TRPCLink<TRouter>[] }) => TRPCClient<TRouter>;
};
export const useTRPCClient = <TRouter extends AnyRouter>(trpc: TRPC<TRouter>, url: string, wsUrl?: string) => {
const [trpcClient] = useState(() => {
const http = httpLink({
url,
fetch: async (input, init) => {
const fetch = getFetch();
return fetch(input, { ...init, credentials: 'include' });
},
headers: () => {
const originURL = window.location.href;
return {
'origin-url': originURL,
};
},
});
const wsClient = wsUrl ? createWSClient({ url: wsUrl }) : null;
const ws = wsClient ? wsLink({ client: wsClient }) : null;
return trpc.createClient({
links: ws
? [
splitLink({
condition: (op) => op.type === 'subscription',
true: ws,
false: http,
}),
]
: [http],
});
});
return trpcClient;
};
createClient: (opts: { links: TRPCLink<TRouter>[] }) => ReturnType<typeof createTRPCClient>;
correct?
Issue 2: the AnyRouter type deprecation, how can that be resolved?