Search code examples
reactjsredux-toolkitrtk-query

Can a useQuery hook skip itself?


Instead of skipping a query by passing skipToken to its useQuery hook, is is possible for the query to skip itself?

In the RTK Query API Reference section Setting default headers on requests, there is an example where prepareHeaders checks the store for an auth token, and if it is there then it sets it as the Authorisation header for the request. This is exactly what I am doing in my app.

But if the token is not in the store then the request would fail with HTTP 403. Even worse, that failure is cached by RTKQ so the useQuery hook will fail again next time, even if the auth token has become available in the meantime.

So in that case I want to query to be skipped. I can only see 2 ways to do this, and neither is satisfactory:

  • One way would be for the React component to check the store and pass skipToken if the auth token is not in the store. But this is a pain because I have to remember to do this same check in every component that uses the query. And I think the auth mechanism should be internal to the query code.
  • Another possibility is to override queryFn, do the check in there, and return an error if the auth token isn't present. This is a bit clunky, and it still leaves the same problem as before: the failure is cached, so the useQuery hook will keep returning an error even what the auth token becomes available.

I would like a way for the query to be able to be able to skip itself if the auth token is not present (as if skipToken has been passed into the useQuery hook). Is it possible to do something like this?


Solution

  • No, there is no such mechanic of skipping itself.

    I'd suggest adding an authenticated tag to all your queries that need authentication and just invalidating that tag from your login mutation.