如何使用 RTK 查询编排 API 调用?
我是第一次使用 RTK 查询,想知道编排呼叫的“正确”方法?
例如,我需要调用登录 api,获取令牌,然后在所有后续调用中使用该令牌。对于像 Saga 这样的东西,我只会在登录 API 调用的成功操作上触发这些 API 调用。但是对于 RTK 查询?...
我真的需要有一个 thunk 或让一个组件在状态更改(指示商店中的登录令牌)时手动触发 RTK 查询吗?必须有一些官方更好的方法来做到这一点,对吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您将在登录表单中触发登录突变。这将由外部切片监听,并且令牌将存储在该切片中。
接下来的每个查询都可以通过 baseQuery 的
prepareHeaders
函数来使用该登录令牌。由于您将在需要它们的组件中使用这些查询,并且这些组件将在登录后呈现,因此它们不需要关心“我现在是否登录”的问题?
请参阅文档中的此示例
当然,所有也就是说,您一开始就不应该拥有 JavaScript 可以访问的令牌。最好的做法是将其放在 httpOnly cookie 中。
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.