how can I globally set a "middleware" callback for all onErrors on my React Query calls?
this is a little specific but Im struggling on it
Im using the TRPC server as a BFF for my backend and for every call on the client I'm sending a token so backend can authenticate it, when the token is not valid anymore api return status code 403 (forbidden).
what I want to do in my FE is that every onError call I check the status to see if it is forbidden and if it is I will redirect the user and do some stuff (like remove the token from storage and redirect)
since Im using ReactQuery I know that where I instantiate the QueryClient I can pass some default options and there's a callback for onError, but I cannot follow this way cause its on the top of the application and the rest "arent loaded" such as the router cause its bellow the QueryClient provider, so I can not access the Navigator from react router dom because it dont exist on that scope.
I think what I can do is maybe impossible, but Im asking that because I would like suggestion for what I can do instead
3 Replies
I can try do what I can with the things available such as window.location and remove from storage by hand but..
maybe can I set a callback for onErrors calls somewhere else in another scope where my things already lives?
See this custom link.
https://trpc.io/docs/client/links
Links Overview | tRPC
Links enable you to customize the flow of data between the tRPC Client and Server. A link should do only one thing, which can be either a self-contained modification to a tRPC operation (query, mutation, or subscription) or a side-effect based on the operation (such as logging).
within the batch link i override the fetch and do custom things inside there. you can see the response codes and what not there. you also have access to the client as you can see i'm updating the local session in here