asliwinski
asliwinski

Reputation: 1714

React Query keeps retrying despite 'enabled' set to false

I want to set up my query so that it retries infinitely unless it receives a particular type of an error, such as 404 or 401. I couldn't find a way to do it with React Query API, but I figured I can provide a callback setting enabled to false to my fetch wrapper like so:

async function fetchItems(onError) {
  return fetch("https://pokeapi.co/api/v2/404").then(async (response) => {
    if (response.ok) {
      return await response.json();
    } else {
      if (response.status === 404) onError();
      throw new Error(response.statusText);
    }
  });
}

export default function App() {
  const [isEnabled, setIsEnabled] = useState(true);
  const { data } = useQuery(
    "data",
    () => fetchItems(() => setIsEnabled(false)),
    {
      enabled: isEnabled,
      retry: true
    }
  );

  return <div>{data}</div>;
}

Sandbox

This, however, doesn't work and it keeps on retrying despite enabled being set to false right after the first call. Am I doing something wrong, does it work as designed or should I file a bug report?

Upvotes: 5

Views: 6659

Answers (1)

buzatto
buzatto

Reputation: 10382

retry takes also a function with count, error params. query will rerun if function on retry returns truthy. in this way you need to throw status at your fetch function and implement a boolean logic like:

if (response.status === 404) onError();
throw new Error(response.status);
...
retry: (count, {message: status}) => (status !== '404' && status !== '401')

Upvotes: 4

Related Questions