trpc / trpc

๐Ÿง™โ€โ™€๏ธ Move Fast and Break Nothing. End-to-end typesafe APIs made easy.
https://tRPC.io
MIT License
34.65k stars 1.23k forks source link

feat: Automatic query invalidations #5264

Open jtmarmon opened 9 months ago

jtmarmon commented 9 months ago

Describe the feature you'd like to request

I would love the ability to define invalidations in my query/mutation definitions, so that queries can be automatically invalidated without having to call it manually on the client.

Describe the solution you'd like to see

Example Given a mutation called updateUser and a query called getUser. In the client right now, everywhere you call updateUser, you need to remember to invalidate getUser to prevent staleness.

Instead, it'd be great if this could be done automatically for you if your definition looks like so:

const usersRouter = router({
   getUser: procedure.input(...).query(() => ...),
   updateUser: procedure.input(...).invalidates('getUser').mutation(...)
});

Describe alternate solutions

n/a

Additional information

No response

๐Ÿ‘จโ€๐Ÿ‘งโ€๐Ÿ‘ฆ Contributing

Funding

Fund with Polar

Glinkis commented 9 months ago

This seems like it wouldn't be possible without breaking the server/client code separation, since the router is defined on the server, and only the ttpes are available to the client.

KATT commented 9 months ago

I don't think this would not require a breaking considering our RPC-spec can return more data

{
  result: {
    data: TOutput; // output from procedure
  }
}

A mutation could return e.g.

{
  result: {
    data: TOutput; // output from procedure
  },
  invalidates: [
    ['post', 'list'], // invalidate post.list
    ['post', 'byId', 1], // invalidate post id 1
  ]
}
KATT commented 9 months ago

It will be tricky in the @trpc/react-query package though with how/when we actually could automatically trigger invalidations and how loading state would be, but not impossible.

Would a mutation stay "loading" until everything has been invalidated? Timing matters here if you do e.g. a redirect as a result of a mutation - you'd likely want the invalidation happen after a route change - think in the case of deleting a post you're viewing as an example. Would likely need to be configurable.

KATT commented 9 months ago

My recommendation is to Invalidate full cache on every mutation until you actually have a need for anything else

DawidWraga commented 7 months ago

This would be a really great addition to TRPC. @KATT perhaps zenstacks implementation could be a useful source of inspiration