Skip to content

Commit

Permalink
Fix "Worker was terminated" error on unmount
Browse files Browse the repository at this point in the history
  • Loading branch information
CyberAndrii committed Sep 14, 2024
1 parent 462d7ed commit 73e7c76
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
12 changes: 12 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,16 @@ describe('Document', () => {

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

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

const { unmount } = render(
<Document file={pdfFile} onLoadProgress={onLoadProgress} options={{ stopAtErrors: true }} />,
);

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 @@ -8,6 +8,7 @@ import invariant from 'tiny-invariant';
import warning from 'warning';
import { dequal } from 'dequal';
import * as pdfjs from 'pdfjs-dist';
import type { DocumentInitParameters } from 'pdfjs-dist/types/src/display/api.js';

import DocumentContext from './DocumentContext.js';

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 73e7c76

Please sign in to comment.