I have a token, that I put in localStorage, then I have this below in a global context, in authProvider
const [accessToken, setAccessToken] = useState<string | null>(
localStorage.getItem(ACCESS_TOKEN) ?? null,
);
Then after login, if people check remember me, we put that in localStorage, otherwise we just setAccessToken(token) so it's stored in global state, so we can have
const {accessToken} = useAuth()
And in this component I have console.log and see that we definitely have the token, it's not null or undefined. However, in my useQuery it will result in some data fetching error.
But if I wrote something extra such as
const token = localStorage.getItem(ACCESS_TOKEN)?? accessToken;
then use this token, instead of accessToken directly from useAuth, I did not have errors.
Component B:
const {accessToken} = useAuth() as AuthContextType;
// have to add a line below to make it work but it doesn't make sense to me if I already do it in useAuth
const token = localStorage.getItem(ACCESS_TOKEN) ?? accessToken;
// fetch data
const {isLoading: isLoadingEmail} = useQuery(
['emailData', token],
async () => {
return await axiosClient.get(ACCOUNT_EMAIL_URL, {
params: {
token,
},
});
},
{
onSuccess: (res) => {
setEmail(res.data.email);
},
onError: (err) => {
console.error(err);
setEmailErr('error loading data');
},
},
);
Why would this happen? Isn't this repeated as I already checked the local storage one in the useAuth?