tRPCttRPC
Powered by
LopaisL
tRPC•4mo ago•
6 replies
Lopais

Type stable "combine" function for "useQueries"

Hey all,

im trying to use a https://tanstack.com/query/latest/docs/framework/react/reference/useQueries#combine function to combine the results from multiple queries together. As the documentation says, the combine function should be referentially stable.

Im trying to get this typed properly, but getting the proper type for the "result" parameter of the combine function is a little crazy the way I have it working now, see example below.

I must be missing something obvious to make this less crazy, any tips?

Thanks! ❤️

const trpc = useTRPC();

// Stable reference to the "combine" function
const combineData = useCallback(
  (
    // --- THIS IS CRAZY ---
    result: Parameters<
      Exclude<
        Parameters<
          typeof useQueries<
            Array<
              ReturnType<typeof trpc.projects.plannedTime.get.queryOptions>
            >
          >
        >[0]["combine"],
        undefined
      >
    >[0],
  ) => return result.flatMap((r) => r.data ?? []),
  [trpc],
);

const data = useQueries({
  queries: sections.map((section) =>
    trpc.projects.plannedTime.get.queryOptions({
      projectId,
      startDate: section.start,
      endDate: section.end,
    }),
  ),
  combine: combineData,
});
const trpc = useTRPC();

// Stable reference to the "combine" function
const combineData = useCallback(
  (
    // --- THIS IS CRAZY ---
    result: Parameters<
      Exclude<
        Parameters<
          typeof useQueries<
            Array<
              ReturnType<typeof trpc.projects.plannedTime.get.queryOptions>
            >
          >
        >[0]["combine"],
        undefined
      >
    >[0],
  ) => return result.flatMap((r) => r.data ?? []),
  [trpc],
);

const data = useQueries({
  queries: sections.map((section) =>
    trpc.projects.plannedTime.get.queryOptions({
      projectId,
      startDate: section.start,
      endDate: section.end,
    }),
  ),
  combine: combineData,
});
useQueries | TanStack Query React Docs
The useQueries hook can be used to fetch a variable number of queries: tsx const ids = [1, 2, 3] const results = useQueries({ queries: ids.map((id) = ({ queryKey: ['post', id], queryFn: () = fetchPost...
useQueries | TanStack Query React Docs
tRPCJoin
Move Fast & Break Nothing. End-to-end typesafe APIs made easy.
5,015Members
Resources
Recent Announcements

Similar Threads

Was this page helpful?

Similar Threads

Cancel useQueries with single function
vildantursicVvildantursic / ❓-help
3y ago
v10 useQueries does not return a stable reference
AlexWayneAAlexWayne / ❓-help
2y ago
anyone used combine function on useQueries? I can't figure where to place it in case of tRPC
vildantursicVvildantursic / ❓-help
2y ago