IdoPesok / zsa

https://zsa.vercel.app
MIT License
829 stars 25 forks source link

Equivalent of trpc's `useUtils` #180

Closed musjj closed 3 months ago

musjj commented 4 months ago

https://trpc.io/docs/client/react/useUtils

One of my favorite things about tRPC is that it automatically handles your query keys in a typesafe way:

const utils = trpc.useUtils();
utils.post.all.refetch();

This way you don't have to juggle keys manually.

It looks like that zsa has a few utilities to make query keys more typesafe, but it's still a lot of boilerplate that you have to constantly synchronize:

export const QueryKeyFactory = createServerActionsKeyFactory({ 
  getPosts: () => ["getPosts"],  
  getFriends: () => ["getFriends"],  
  getPostsAndFriends: () => ["getPosts", "getFriends"],  
  somethingElse: (id: string) => ["somethingElse", id],  
  getRandomNumber: () => ["getRandomNumber"], 
})  

So it would be nice if zsa can provide an equivalent to tRPC's useUtils that would absolve the need for all of this manual work.

IdoPesok commented 4 months ago

Hi, I totally concur that useUtils is awesome and understand your frustration with juggling keys manually.

The current recommended way to do this is you can use React Query and its useQueryClient hook. I assume you have already read the docs about this but linking it here just in case.

As for why zsa can't provide a direct equivalent - it's because you are in some way doing the defining/juggling of keys when you are defining your routes in tRPC. Since server actions aren't typed under a router, there is no way really to do a typesafe useUtils since there are no key/value pairs to work off of. Hopefully that makes sense. If you have an idea happy to hear out how it would work.

I am working on a router for zsa - will think about how maybe zsa can provide a query key factory that automatically gets synchronized based on the router types. For context, when using the router there is only one "active" server action endpoint that takes in the route key and routes the input to the corresponding function/action.

Will keep you posted. Thanks for the feedback.

musjj commented 3 months ago

Is there a reason why this was closed? Was this feature implemented already?