3

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:

  1. Download process is started, the file will automatically download once the file is ready
  2. 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:

  1. API 1 - used for displaying the first notification. I use refetch option with this to check if the download is ready.

  2. 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.

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Manny
  • 134
  • 2
  • 15
  • 3
    I'ld say: you're feature shouldn't be scoped for `DownloadModal` component, b/c you expect it to work even outside of it. Therefore, I'ld move the logic up to an overarching component which doesn't get unmounted, e.g. `App` or the alike. – NotX Jun 05 '23 at 14:30
  • I also think about using `context`, so you can just take a try. – haptn Jun 07 '23 at 05:16

0 Answers0