I am using useQuery
and its refetch
option to download a file in the frontend. The download process is of two steps, and I am displaying the below notifications to the users:
- Download process is started, the file will automatically download once the file is ready
- The download has now been completed
Both these notifications are displayed to the user, and the idea is to allow the user to navigate anywhere in the application while the download is being processed.
There are two APIs:
API 1 - used for displaying the first notification. I use
refetch
option with this to check if the download is ready.API 2 - used for downloading the file once the API returns "Ready for download" status
For this, I have created a custom hook
where I call the useQuery
for each API
Custom hook structure:
export const useFileDownload = () => {
const [fileReady, setFileReady] = useState(false);
const { isError, isLoading, mutate } = useDownloadBegin({ //this uses useQuery with refetch option
onSuccess: (data) => {
setFileReady(true);
}
});
const { isError, isLoading, mutate } = useDownloadFile({ //this downloads file using useQuery
enabled: fileReady;
. . .
});
}
My Component:
<DownloadModal {props} />
Download Modal:
export const DownloadModal = ({...props}) => {
const { isDownloading } = useFileDownload();
return(
<>Download Modal</>
)
}
What is the issue?
Once I navigate to another page, API 1 stops getting executed, and I am never able to download the file using API 2. It works absolutely fine if I stay on the same page.
I believe, the hook does not get executed once I go to another page, as the component gets unmounted.
How do I make sure that hook gets executed asynchronously even when navigated away from the component?
What have I tried?
I explored different options available in tanstack useQuery like refetchIntervalInBackground
.
Also, since I do not have a store
in my application, I am trying to work around context
to see if I can use it for my purpose. But, I am still not sure about it.