Luka
Luka13mo ago

Merging two clients into one

I have two clients. One for react-query for client components and one for server components. I wanna be able to call .query() or .useQuery() from the same object so you get one object for API calling on both server and client. I tried combining the two client objects with Object.assign. The types work as you can see in the screenshot but the object returned from Object.assign is empty. Wanna know what's the reason for that or what's the better way of doing this
No description
2 Replies
Nick
Nick13mo ago
Both are implemented with JS proxies, so you would have to write your own proxy wrapper over the two of them But I really just question why Is it so hard to import two variables? or grab the client from useUtils?
Luka
LukaOP13mo ago
just wanted to have one api object, seemed like a better workflow you pretty much would have access to both clients under one trpc source small update if anyone is gets interested in this in the future. you can merge the two proxies using this function
function mergeProxies<T, U>(client: T, server: U): T & U {
const proxy = new Proxy(
{},
{
get(_, prop) {
return (client as any)[prop] || (server as any)[prop];
},
},
);
return proxy as T & U;
}
function mergeProxies<T, U>(client: T, server: U): T & U {
const proxy = new Proxy(
{},
{
get(_, prop) {
return (client as any)[prop] || (server as any)[prop];
},
},
);
return proxy as T & U;
}
but the caveat is that when you get to your procedure/endpoint property the object that comes first when called in the function takes precedence.
export const api = mergeProxies(client, server);
export const api = mergeProxies(client, server);
like this you will get error Cannot access cart.getCartItems on the server. You cannot dot into a client module from a server component. You can only pass the imported name through. if you do
export const api = mergeProxies(server, client);
export const api = mergeProxies(server, client);
you will get an error client[procedureType] is not a function so theres really no way to merge the two clients and have the auto suggestions the way it is in the screenshot at the start. some merge function from trpc library could be cool for this, or a client for nextjs 13 that allows both simple queries for server components and react-query for client components