Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

140
Views
Is there a way to fetch data only when token Is available?

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...

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!