Skip to content

Query keeps retrying despite 'enabled' set to false after first error #1380

@asliwinski

Description

@asliwinski

Describe the bug
I want to set up my query so that it retries infinitely unless it receives a particular type of error, such as 404 or 401, at which point it should stop immediately (basically retry only when the error is network related). I couldn't find a way to do it with React Query API (is there any?), but I figured I can provide a callback setting enabled to false to my fetch wrapper and call it when such an error occurs.

To Reproduce
Run the following code:

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

Observe that the query is being called more than once.

Expected behavior
Stop retrying as soon as enabled becomes false.

Additional context
Sandbox

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions