Skip to content

Commit

Permalink
Fix "Worker was terminated" error on unmount (#1877)
Browse files Browse the repository at this point in the history
  • Loading branch information
CyberAndrii authored Sep 18, 2024
1 parent 70b5e6d commit 2ff8ff6
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
10 changes: 10 additions & 0 deletions packages/react-pdf/src/Document.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -695,4 +695,14 @@ describe('Document', () => {

vi.mocked(globalThis.console.error).mockRestore();
});

it('does not throw an error on unmount', async () => {
const { func: onLoadProgress, promise: onLoadProgressPromise } = makeAsyncCallback();

const { unmount } = render(<Document file={pdfFile} onLoadProgress={onLoadProgress} />);

await onLoadProgressPromise;

expect(unmount).not.toThrowError();
});
});
12 changes: 6 additions & 6 deletions packages/react-pdf/src/Document.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {
import useResolver from './shared/hooks/useResolver.js';

import type { PDFDocumentProxy } from 'pdfjs-dist';
import type { DocumentInitParameters } from 'pdfjs-dist/types/src/display/api.js';
import type { EventProps } from 'make-event-props';
import type {
ClassName,
Expand Down Expand Up @@ -507,10 +508,9 @@ const Document: React.ForwardRefExoticComponent<
return;
}

const documentInitParams: Source = {
...source,
...options,
};
const documentInitParams: DocumentInitParameters = options
? { ...source, ...options }
: source;

const destroyable = pdfjs.getDocument(documentInitParams);
if (onLoadProgress) {
Expand All @@ -521,7 +521,7 @@ const Document: React.ForwardRefExoticComponent<
}
const loadingTask = destroyable;

loadingTask.promise
const loadingPromise = loadingTask.promise
.then((nextPdf) => {
pdfDispatch({ type: 'RESOLVE', value: nextPdf });
})
Expand All @@ -534,7 +534,7 @@ const Document: React.ForwardRefExoticComponent<
});

return () => {
loadingTask.destroy();
loadingPromise.finally(() => loadingTask.destroy());
};
},
[options, pdfDispatch, source],
Expand Down

0 comments on commit 2ff8ff6

Please sign in to comment.