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

Viewed 543

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?

1 Answers

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,
  });


Related