Skip to content

DRAFT/STRAWMAN/not currently intended for merging: add trpc.foo.useQuery back? #6563

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from

Conversation

mmkal
Copy link
Contributor

@mmkal mmkal commented Feb 24, 2025

Related to #6240 - CC @juliusmarminge

This PR isn't really a "pull" request - just as a place to allow discussion with commenting on code inline etc. if it's helpful.

Since @KATT suggested something to fill the gap between the old react-query API and the new one might be welcome, I thought I'd just poke around and see what the dumbest possible implementation of it might look like.

I want to be clear though that I'm aware I wasn't involved in the discussions around the new API and what the specific pitfalls of the old one were, so I am very sorry if this is just prompting people to repeat themselves!

🎯 Changes

For now, this just adds a useQuery(...) method to the DecorateQueryProcedure interface. Something similar would be needed for useMutation and useSubscription and useInfiniteQuery, but I didn't bother with those because I wanted to sanity check/find out pitfalls first.

DX for consumers wise, I think it brings back pretty much the usage pattern as before, along with all the shortcomings about new react-query features and so on.

Maintenance wise:

Code: it doesn't seem bad? I haven't been in the weeds in trpc for a while so I don't remember which helpers came into existence and when, but all I really did was copy-paste the TRPCQueryOptions interface into a TRPCUseQueryResult interface, with identical generics, but made the return types of each overload UseQueryResult<TData, TRPCClientErrorLike...>. The runtime implementation was trivial - just do what we're already doing for queryOptions and pass it to a useQuery imported from @tanstack/react-query

Dependencies: it's worth noting that the import from @tanstack/react-query is going from import type {...} to import {...} because we're now importing useQuery.

Of course even if this approach, there's more to consider than just the code. Test and docs would of course be needed, and decisions needed about the docs. trpc would now need to decide when it promotes which variant. My intuition says to promote trpc.greeting.useQuery() by default, and suggest useQuery(trpc.greeting.queryOptions()) as an escape hatch, for when you need to override one of the options, use a new react-query feature, or use a different react-query version.

Also, it's hard to predict what'll happen in future. But, if react-query came out with a new version that renamed queryFn to queryFunction or something, I think it'd be simple for users to do something like "react-query-v123": "npm:@tanstack/react-query@^123.0.0" in their package.json, then something like this in their code:

import {trpc} from '~/wherever'
import {useQuery} from 'react-query-v123'

export default function Foo() {
  const hello = trpc.hello.useQuery()
  
  const {queryFn, ...goodbyeOptions} = trpc.goodbye.queryOptions()
  const goodbye = useQuery({...goodbyeOptions, queryFunction: queryFn})

  return <>{hello.data} {goodbye.data}</>
}

Copy link

railway-app bot commented Feb 24, 2025

This PR was not deployed automatically as @mmkal does not have access to the Railway project.

In order to get automatic PR deploys, please add @mmkal to the project inside the project settings page.

Copy link
Contributor

coderabbitai bot commented Feb 24, 2025

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

vercel bot commented Feb 24, 2025

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 Feb 26, 2025 8:31pm
og-image ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 26, 2025 8:31pm
1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
www ⬜️ Ignored (Inspect) Visit Preview Feb 26, 2025 8:31pm

Copy link

pkg-pr-new bot commented Feb 24, 2025

Open in Stackblitz

@trpc/client

npm i https://pkg.pr.new/trpc/trpc/@trpc/client@6563

@trpc/next

npm i https://pkg.pr.new/trpc/trpc/@trpc/next@6563

@trpc/server

npm i https://pkg.pr.new/trpc/trpc/@trpc/server@6563

@trpc/react-query

npm i https://pkg.pr.new/trpc/trpc/@trpc/react-query@6563

@trpc/tanstack-react-query

npm i https://pkg.pr.new/trpc/trpc/@trpc/tanstack-react-query@6563

@trpc/upgrade

npm i https://pkg.pr.new/trpc/trpc/@trpc/upgrade@6563

commit: 76167bf

Copy link
Member

@juliusmarminge juliusmarminge left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR, good way to start a more formal discussion!

The new structure of the new package allows for introducing this without much overhead so maintenance wise this would be fine.

One problem is we'd need to reintroduce multiple init methods in order to not expose react hooks for server callers for example?

My intuition says to promote trpc.greeting.useQuery() by default, and suggest useQuery(trpc.greeting.queryOptions()) as an escape hatch

My main problem with this is you're leading developers down a "bad path" since they would not benefit from eslint rules nor the compiler, two aspects that this new API that isnt talked about

We'll definitely discuss this, both internally and on this PR though.

@@ -87,6 +93,8 @@ export interface DecorateQueryProcedure<TDef extends ResolverDef> {
*/
queryOptions: TRPCQueryOptions<TDef>;

useQuery: TRPCUseQueryResult<TDef>;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could flag this so it's not exposed by default, and people coming from the old API could enable to have a more familiar API.

Something like:

createTRPCOptionsProxy<AppRouter, {
  enableOldHooks: true
}>()

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah I guess, but as you pointed out in #6508 (reply in thread) there is already away to get the old API, if it is indeed considered "old". My hope with this is to figure out if we can keep around the old API for most use cases indefinitely, because it's better DX. But if that were the direction making it opt in and using the label "old" wouldn't make sense.

If we'd just be adding it to help people migrate extra slowly, then yeah that could be sensible.

@Nick-Lucas
Copy link
Contributor

Just to echo what Julius is saying, the old integration doesn't look like it's going to age well when React Compiler comes out, and there's a long-standing issue where eslint's hooks rules don't lint it because the rules don't consider our proxy to be valid. The classic client permits (and in the case of our polymorphism work actively encourages) patterns which break the rules of hooks, so will not compile in the future, and we should have emphasised that in the announcement post.

I would love to find a way to support custom helpers where teams and codebases want these sorts of wrappers (at their own peril) but I personally think the core surface area of the TRQ client should avoid anything that could become a foot gun in the wrong hands

@@ -1,4 +1,9 @@
import type { DataTag, QueryClient, QueryFilters } from '@tanstack/react-query';
import {
useQuery,
Copy link
Member

@juliusmarminge juliusmarminge Feb 24, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This might be rejected by Next.js if using server components like this:

https://trpc.io/docs/client/tanstack-react-query/server-components#5-create-a-trpc-caller-for-server-components

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah I see. I just checked and it seems you're right, that useQuery.ts has a 'use client' directive: https://github.com/TanStack/query/blob/74db58292e0b4e4bcf6d8ff720c6770df26a26df/packages/react-query/src/useQuery.ts#L1

Which is a bit of a surprise to me, I'd have thought it'd be left to the user to avoid this kind of problem. Not sure if that could be changeable in tanstack, but I imagine they have thought it through much more than I have.

@mmkal
Copy link
Contributor Author

mmkal commented Feb 26, 2025

Re compiler and eslint: this is scope creep, but I just pushed a change which wraps rules-of-hooks in the eslint config to enable it for trpc.foo.useQuery() expressions, along with an example of a violation in Greeting.tsx:

image

It's a hack, which depends on the implementation of RuleOfHooks.ts, clearly a better solution would be an actual resolution to facebook/react#25065. But, I also was able to make a very small modification to eslint-plugin-react-hooks which would allow for resolving that bug, either in a configurable way or not, so maybe the react team would accept a pull request.

I don't know about React Compiler, but maybe something similar would be possible?

@Nick-Lucas
Copy link
Contributor

Nick-Lucas commented Feb 26, 2025

I don't know about React Compiler, but maybe something similar would be possible?

So you can get an early view on what's acceptable with https://www.npmjs.com/package/eslint-plugin-react-compiler - it's been a while since I tried it but my work codebase uses tRPC's polymorphism and because it involves passing hooks through props it unfortunately rejects that code. Most tRPC code might go unrejected though I'm not sure if anything would de-opt under the hood because of the chained hooks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy