有没有办法只有在可用时才获取数据?
大家好,
我的反应代码有一个小问题,希望这里有人能够帮助我解决它。
基本上我是从端点获取数据(多个) 我正在使用Axios并进行反应查询。
在我的获取请求中,我有安全标头,一个是授权。 用户被登录时发送到会话存储的令牌授权。
我从会话存储中获取令牌,然后将其放在授权标题中。 我现在的问题是在用户登录之前,令牌=== null 然后,我的Get请求在用户登录之前运行,以空白令牌为单位。
当用户最终登录时,没有获取数据,因为授权标头中的内容为null,但是当我刷新页面时,数据将被获取,因为当时令牌已经交付,而不是= null。
我不知道您是否完全理解原因很擅长解释,但是如果您这样做,那么无论如何都可以解决这个问题。
谢谢...
Good day all,
I have a little issue in my react code and I hope someone here would be able to help me fix it.
Basically I am fetching data from an endpoint (multiple)
Am using axios and react query.
In my get request, I have security headers and one is Authorization.
User is authorized by a token sent to session storage when he / she login.
I get the token from session storage and place it in my authorization header.
My problem now is before the user login, the token === null
and my get request runs before the user logins leaving it with an empty token.
When the user finally logins, no data is fetched because what is in the authorization header is null but when I refresh the page, the data is fetched because at that time the token was already delivered and not = null.
I don't know if you fully understand cause am pretty bad at explaining but if you do, is there anyway to fix the issue.
thanks...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用的是RTK,则可以使用
skip
:并设置
skip
在可用的令牌时为falseIf you're using RTK, you may use
skip
:and set
skip
to false when the token is available由于令牌是您获取的依赖性,因此应该转到
querykey
。然后,只要令牌为null,就可以通过启用
选项禁用查询。如果令牌更新(从null更改为值),并且该重新呈现您的组件,则查询将自动运行,因为查询密钥会更改。如果令牌为
null
,则查询将不会运行。since the token is a dependency to your fetch, it should go to the
queryKey
. Then you can disable the query via theenabled
option for as long as the token is null.if the token updates (changes from null to a value), and that re-renders your component, the query will run automatically because the query key changes. The query will not run if the token is
null
.