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
CodePudding user response:
If you're using RTK, you may use skip
:
const [skip, setSkip] = useState(true);
const { isUninitialized, isSuccess, isLoading } = useSomeQuery(token, {
skip
});
and set skip
to false when the token is available
CodePudding user response:
since the token is a dependency to your fetch, it should go to the queryKey
. Then you can disable the query via the enabled
option for as long as the token is null.
const token = useTokenFromLocalStorage()
useQuery(
["user", token],
() => fetchUser(token),
{
enabled: !!token
}
)
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
.