Ashik
Ashik

Reputation: 3428

react-query: Refetch if and only if there is no error

On my root component, I have used use query to get the user details. but the problem is before I sign up or sign in, it refeches too many times. as a result I can't even fill up the signUp/signIn form smoothly.

enter image description here

Is there any way, so that It will refetch only if the callback function returns no error?

This is, what I have tried

const FetchCurrentUser = async () => {
  setAuthToken(localStorage.token);
  const {
    data: { user },
  } = await axios.get(`${process.env.API_URL}/api/users/auth`);

  return user;
};

const RouterController = () => {
  const { data: updatedUser, isLoading, error: fetchError } = useQuery(
    "user",
    FetchCurrentUser,
   
  );
}

Upvotes: 6

Views: 16723

Answers (4)

Akshay Vijay Jain
Akshay Vijay Jain

Reputation: 15945

If you want to stop retrying after failed api request, you can make use of retry option and set it to false

useQuery('',fn,{
retry:false
})

https://react-query-v3.tanstack.com/reference/useQuery#_top

Upvotes: 4

Sky
Sky

Reputation: 402

there is a simple way to stop this API call before the required data is ready. All you need to do is just to set enabled: false in the query options and then set it to true when the data is ready.

const RouterController = () => {
  const { data: updatedUser, isLoading, error: fetchError } = useQuery(
    "user",
    FetchCurrentUser,
   {
     enabled: !!requiredData,
   },
  );
}

However, I your code structure is not so clear. Therefore, I think there might be other problems with your code structure.

Upvotes: 0

Sky
Sky

Reputation: 402

Another way to handle this issue is to set 'enabled: false' in query options and whenever u want the API to be called, use the refetch. in your case it would be like this:

const RouterController = () => {
  const { data: updatedUser, isLoading, error: fetchError, refetch } = useQuery(
    "user",
    FetchCurrentUser,
    {
      enabled: false,
    },
  );

  const handleClick = () => {
    refetch();
}
}

Upvotes: 0

Otacilio Lacerda
Otacilio Lacerda

Reputation: 368

I am not sure if I understood the question correctly. I am assuming you are trying to fetch the user data but if it fails you do not want to retry, is that correct?

React Query has some defaults that can might tricky to new users. From the docs:

Queries that fail are silently retried 3 times, with exponential backoff delay before capturing and displaying an error to the UI.

For mode details check Important Defaults

You can also deactivate the automatic request by setting the enabled config property to false on the useQuery hook and use the refetch function to trigger the request manually.

Upvotes: 5

Related Questions