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;
};
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;
};