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

220
Views
Is there a way to handle react useQuery with status code 401 without 10 seconds of loading time?

When the react page is initially loaded will it perform a me-query. The me-query's intention is to get the current user if they have an active session.

In the authentication middleware will this code be run:

function authenticate(req: Request, res: Response, next: NextFunction) {
  if (!req.session || !req.session.userId) {
    return res
      .status(401)
      .json({ error: "Missing login, must login/register" });
  }
  next();
}

And in the client will it perform this

export const fetchUser = async (): Promise<User> => {
  const res = await axios.get(`/profile`);

  if (res.data) return res.data;

  if (res.status === 401) throw new Error("Could not get profile"); 
  throw new Error("Could not get profile");
};


const { data, error, isLoading, isFetching, status } = useQuery<User, Error>(
   "user",
   fetchUser
);

What is currently happening is that it re-runs the same query multiple times. But if I change return res.status(401).json({ error: "Missing login, must login/register" }); to return res.status(200).json({ error: "Missing login, must login/register" });, then it returns immediately, and I won't have to look at my page refreshing for 10 seconds.

Is it possible to make useQuery only perform one request to the server? Preferably getting the fast response as I am getting with status of 200?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

I found a solution. It is possible to set the amount of retries one can do. I set mine to 0, thus avoiding the long wait.

 const { data, error, isLoading, isFetching, status, failureCount } = useQuery<
    User,
    Error
  >("user", fetchUser, {
    retry: 0,
  });


over 4 years ago · Santiago Trujillo 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!