Gabriel
Gabriel4w ago

How can I automatically use react's cache with tRPC on server side?

I have this in my repo:
import { cache } from "react";
import { headers } from "next/headers";

import { createCaller, createTRPCContext } from "@kdx/api";
import { auth } from "@kdx/auth";

/**
* This wraps the `createTRPCContext` helper and provides the required context for the tRPC API when
* handling a tRPC call from a React Server Component.
*/
const createContext = cache(async () => {
const heads = new Headers(headers());
heads.set("x-trpc-source", "rsc");

return createTRPCContext({
auth: await auth(),
headers: heads,
});
});

export const api = createCaller(createContext);
import { cache } from "react";
import { headers } from "next/headers";

import { createCaller, createTRPCContext } from "@kdx/api";
import { auth } from "@kdx/auth";

/**
* This wraps the `createTRPCContext` helper and provides the required context for the tRPC API when
* handling a tRPC call from a React Server Component.
*/
const createContext = cache(async () => {
const heads = new Headers(headers());
heads.set("x-trpc-source", "rsc");

return createTRPCContext({
auth: await auth(),
headers: heads,
});
});

export const api = createCaller(createContext);
But, now I need to understand, how should I export the actual functions from the api caller so they are all cached with react's cache? I of course could do something like this
export const uglyGetNotifications = cache(api.user.getNotifications);
export const uglyGetNotifications = cache(api.user.getNotifications);
But I would prefer if I could get an instance of api where all of my endpoints will be using the cache automatically. something like
const notifs = await apiCached.user.getNotifications();
const notifs = await apiCached.user.getNotifications();
0 Replies
No replies yetBe the first to reply to this messageJoin