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

4

6

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,
   
  );
}
Harden answered 6/11, 2020 at 4:29 Comment(0)
R
5

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.

Removable answered 8/11, 2020 at 21:50 Comment(1)
Is there a way to prevent fetching when refetch method get called?Vichy
T
4

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

Tumult answered 30/9, 2022 at 11:34 Comment(0)
B
0

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.

Brickle answered 13/7, 2022 at 17:49 Comment(0)
B
0

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();
}
}
Brickle answered 13/7, 2022 at 17:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.