jJ
tRPC11mo ago
2 replies
j

best practice for invalidating protected queries upon profile switch

I have an app where users can have multiple profiles. I have a protectedProcedure that does a db check on the user and profile ownership as a base.

on the frontend, once user switches profile, I want to invalidate all queries that are "protected".

Well known option is:

const { mutateAsync: switch } = api.switchProfile.useQuery()

...
switch.then(() => {
  // invalidate all, but will also invalidate everything that doesn't need to be invalidated like public procedures
  api.useUtils().invalidate()
  
  // invalidate selective, but harder to scale since i haev to keep adding all protected routes as i go.
  api.useUtils().protected1.invalidate();
  api.useUtils().protected2.invalidate();
  api.useUtils().protected3.invalidate();

  // would be nice to have something like
  api.useUtils().protectedProcedures.invalidate();
}


Above will work but switching profile may not always happen in one spot, or through an explicit call. Server might also return a response that may switch the user's profile.

previously to tRPC, I have done attached the userId to the query key to "protected" queries like queryKey: [arg1, arg2, userId, currentProfileId], which ensured revalidation upon switching through any measure.

But this is manual and requires me to add an arbitrary .input() to the protectedProcedure

I also thought about using queryHashKeyFn at the global level, but can get finicky with SSR/Suspense and feels too hacky, and not to mention it will invalidate ALL, not just protected.

Any suggestions here?
Was this page helpful?