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(";).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?
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?
- try this: {enabled: !isEnabled, retry: true } – Sakshi Commented Dec 9, 2020 at 6:58
- @Sakshi no, my goal is not to disable the query pletely so that it doesn't run at all, which your settings would cause. – asliwinski Commented Dec 9, 2020 at 13:26
1 Answer
Reset to default 4retry 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')