Usually isLoading() returns true if the mutation is currently executing. But whenever I switch tabs and come back to the original tab, isLoading() is false, even if the mutation is still running. Is there another way to check if the mutation is still running where isLoading() stays true even when I switch tabs?
This is where I return a useMutation:
export function exportFunction(
options: UseMutationOptions<string, unknown, Core.Paths.CreateExportDocument.RequestBody>
) {
const logError = useLogError();
return useMutation(
async exportFilter => {
const {data} = await axios.post<Core.Paths.CreateExportDocument.RequestBody, AxiosResponse<string>>(
"/pdncore/api/export/assortmentProducts",
exportFilter
);
const {data: blob} = await axios.get(`/pdncore/api/export/document/excel/${data}`, {responseType: "blob"});
return URL.createObjectURL(blob);
},
{
...options,
onError: (err, vars, context) => {
logError("error", err);
options.onError?.(err, vars, context);
},
}
);
}
Here is where I execute this function
const myMutation = exportFunction({
onSuccess: url => {
const link = document.createElement("a");
link.href = url;
link.download = `export-${new Date().toISOString()}.xlsx`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
},
});
And this is the button I return
<Button
startIcon={myMutation.isLoading ? <CircularProgress size={20} /> : <GetApp />}
disabled={myMutation.isLoading}
onClick={() => myMutation.mutate(exportFilter)}
>
</Button>
The easiest and correct way is to use the useIsMutating hook.
https://react-query.tanstack.com/reference/useIsMutating#_top
Example:
import { useIsMutating } from 'react-query'
const isMutation = useIsMutating({
mutationKey: 'youmutationkey',
exact: true
})
<Button
startIcon={myMutation.isLoading || isMutation > 0 ? <CircularProgress size={20} /> : <GetApp />}
disabled={myMutation.isLoading || isMutation > 0}
onClick={() => myMutation.mutate(exportFilter)}
>
</Button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With