SebasPtschS
tRPC3y ago
12 replies
SebasPtsch

Get Query Key on Server

I'm following some recommended practices from one of the react query maintainers @tkdodo and want to invalidate queries from the server in a type-safe way. As a result of this I want to be able to get the query keys for queries on the server to properly invalidate them using a trpc subscription. Is there a clean way to feed the router definition into getQueryKey?

At the moment what I'm doing is:
/**
 * The main router for the backend, contains all other routers
 */
const appRouter = t.router({
  invalidator: publicProcedure.subscription(() => {
    return observable<TRPCQueryKey>((emit) => {
      ee.on("invalidate", (key) => {
        emit.next(key);
      });

      return () => {
        ee.off("invalidate");
      };
    });
  }),
});

export type AppRouter = typeof appRouter;

const rtrpc = createTRPCReact<AppRouter>();

const qk = getQueryKey(rtrpc.thing.getThing, "1"); // use this along with an eventemitter to invalidate queries on the client


This is not in the react context and I don't really want to import react in order to get the query key
Solution
I wouldn’t couple the backend into the frontend state management by trying to dispatch the query key. Instead dispatch a message relevant to your business logic, and on the frontend turn that into a query key for invalidation and optimistic updates, you’ll have a better time
Was this page helpful?