trpc / trpc

🧙‍♀️ Move Fast and Break Nothing. End-to-end typesafe APIs made easy.
https://tRPC.io
MIT License
34.7k stars 1.24k forks source link

feat: `queryOptions` API #5913

Closed juliusmarminge closed 1 day ago

juliusmarminge commented 2 months ago

If we can focus our RQ wrapper on the queryOptions API, I think we could remove a whole lot of surface area and also provide functionality for all the built-in queryClient methods

import { useSuspenseQuery } from '@tanstack/react-query';
import { createFileRoute, Link } from '@tanstack/react-router';
import { useTRPC } from '~/trpc/react';
import { PostErrorComponent } from './posts.$postId';

export const Route = createFileRoute('/posts/$postId/deep')({
  loader: async ({ params: { postId }, context }) => {
    const data = await context.queryClient.ensureQueryData(
      //  ^?
      context.trpc.post.byId.queryOptions({ id: postId }),
    );

    return { title: data.title };
  },
  meta: ({ loaderData }) => [{ title: loaderData.title }],
  errorComponent: PostErrorComponent,
  component: PostDeepComponent,
});

function PostDeepComponent() {
  const { postId } = Route.useParams();
  const trpc = useTRPC();

  const postQuery = useSuspenseQuery(
    trpc.post.byId.queryOptions({ id: postId }),
  );
  postQuery.data;
  //        ^?

  return (
    <div className="space-y-2 p-2">
      <Link
        to="/posts"
        className="block py-1 text-blue-800 hover:text-blue-600"
      >
        ← All Posts
      </Link>
      <h4 className="text-xl font-bold underline">{postQuery.data.title}</h4>
      <div className="text-sm">{postQuery.data.body}</div>
    </div>
  );
}

If implemented correctly, it should be possible to remove all the currently wrapped functions in favor of using built-in's + queryOptions/useQueryOptions wrappers

queryClient.fetch(trpc.foo.queryOptions())
// instead of
trpc.foo.fetch()

const utils = trpc.useUtils();
const query = utils.foo.queryOptions();

useQuery(query)
//instead of
trpc.foo.useQuery()

Would even solve #2330

railway-app[bot] commented 2 months ago
🚅 Deployed to the trpc-pr-5913 environment in trpc-sse-and-websockets Service Status Web Updated (UTC)
next-prisma-websockets-starter ◻️ Removed (View Logs) Oct 16, 2024 at 2:34 pm
vercel[bot] commented 2 months ago

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
next-prisma-starter ✅ Ready (Inspect) Visit Preview Oct 16, 2024 2:33pm
og-image ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 16, 2024 2:33pm
www ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 16, 2024 2:33pm
github-actions[bot] commented 5 hours ago

This pull request has been locked because we are very unlikely to see comments on closed issues. If you think, this PR is still necessary, create a new one with the same branch. Thank you.