Global scope for react query keys? #3743
Replies: 2 comments 1 reply
-
I guess The best way to achieve this is to either make a default query function that adds the accountId (but then it wouldn't be part of the key, so no refetches when it changes, which is not good), or, make
or, make a hook that creates query keys and uses that context:
I like the last approach best because it goes well with the concept of query key factories: https://tkdodo.eu/blog/effective-react-query-keys#use-query-key-factories |
Beta Was this translation helpful? Give feedback.
-
If anyone else is looking for a solution to this, I've found two after some hours of research:
We went with the 1st solution for now, but if we need more customization down the line, we might switch over to the 2nd solution. As a bonus, it also works with trpc out of the box. Overall, since we're heavily leaning into Postgres RLS for tenant data isolation, we've significantly reduced the surface area for accidentally leaking tenant data, and made it virtually impossible, as there's a single point of failure, and if that fails, we return no data whatsoever. Plus we run tests against data, instead of testing every endpoint. The source of truth lies in the JWT, not developers making sure to properly prefix and filter things. Now with the above setup, there's also a single testable point of failure in the UI, whereby we can guarantee globally that we don't accidentally display any cached data across tenants. Manual namespacing at scale can be error prone, and significantly increases the needed testing surface area (even if it's mostly about UX in the frontend case, than data security). |
Beta Was this translation helpful? Give feedback.
-
In most apps there is the need to scope cached queries by default. Let's say you allow users to use multiple accounts. You'd probably want to scope each and every query to the account the user uses.
If queries are not scoped by default, we have to pass the accountId to every invocation of useQuery like so: useQuery([accountId, ...]).
I'd love to know if queryFn can be bound to a global key like this.
Beta Was this translation helpful? Give feedback.
All reactions