0

I am using RTK Queries for the first time and wondering about the 'correct' way to orchestrate calls?

For example I need to make a call to a login api, get a token and then use that token in all subsequent calls. With something like Saga I would just fire those API calls on the success action of the login API call. But with RTK Queries?...

Do I really need to have a thunk or have a component fire a RTK query manually on a state change indicating the login token in the store? There has to be some official better way to do this right?

1 Answers1

0

You would fire a login mutation in your login form. That would be listened by an external slice and the token would be stored in that slice.

Every query following that could use that login token using the prepareHeaders function of baseQuery. As you would be using those queries in the components that need them, and those components would be rendered after the login, they would not need to be concerned with the question of "am I logged in or not right now"?

See this example from the docs

Of course, all that said you should not have a token accessible to JavaScript in the first place. It would be best practice to have that in a httpOnly cookie.

phry
  • 35,762
  • 5
  • 67
  • 81
  • There is no login form. but anyway I cannot see how this allows other queries to be fired only when the first is fired? You cannot fire a request from the slice so this doesn't seem helpful. The issue is not storing the token, it's only making requests once the token is present. I thought RTK would handle this, apparently it doesnt. – Nathan Brown Mar 09 '22 at 01:10
  • No, the idea of RTKQ is pretty much to query for data in the component that needs it, by using the query hooks there. Of course you can have multiple queries depend on each other in the same component by setting the `skip` option in combination with the loading states of previous query hooks. – phry Mar 09 '22 at 07:17