Skip to content

Commit 7444870

Browse files
committed
Fixing some race conditions of the imports
1 parent 89bd12a commit 7444870

File tree

1 file changed

+24
-26
lines changed

1 file changed

+24
-26
lines changed

packages/react-pdf-js/src/index.tsx

Lines changed: 24 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -84,16 +84,6 @@ export const usePdf = ({
8484
onPageRenderFailRef.current = onPageRenderFail;
8585
}, [onPageRenderFail]);
8686

87-
useEffect(() => {
88-
if (typeof window === 'undefined') return;
89-
90-
import('pdfjs-dist').then(({ GlobalWorkerOptions, version }) => {
91-
GlobalWorkerOptions.workerSrc =
92-
workerSrc ||
93-
`//cdnjs.cloudflare.com/ajax/libs/pdf.js/${version}/pdf.worker.mjs`;
94-
});
95-
}, [workerSrc]);
96-
9787
useEffect(() => {
9888
if (typeof window === 'undefined') return;
9989

@@ -103,23 +93,31 @@ export const usePdf = ({
10393
config.cMapPacked = cMapPacked;
10494
}
10595

106-
import('pdfjs-dist').then(({ getDocument }) => {
107-
getDocument(config).promise.then(
108-
(loadedPdfDocument) => {
109-
setPdfDocument(loadedPdfDocument);
110-
111-
if (isFunction(onDocumentLoadSuccessRef.current)) {
112-
onDocumentLoadSuccessRef.current(loadedPdfDocument);
96+
import('pdfjs-dist').then(
97+
({ GlobalWorkerOptions, getDocument, version }) => {
98+
// Set worker source first
99+
GlobalWorkerOptions.workerSrc =
100+
workerSrc ||
101+
`//cdnjs.cloudflare.com/ajax/libs/pdf.js/${version}/pdf.worker.mjs`;
102+
103+
// Then load the document
104+
getDocument(config).promise.then(
105+
(loadedPdfDocument) => {
106+
setPdfDocument(loadedPdfDocument);
107+
108+
if (isFunction(onDocumentLoadSuccessRef.current)) {
109+
onDocumentLoadSuccessRef.current(loadedPdfDocument);
110+
}
111+
},
112+
() => {
113+
if (isFunction(onDocumentLoadFailRef.current)) {
114+
onDocumentLoadFailRef.current();
115+
}
113116
}
114-
},
115-
() => {
116-
if (isFunction(onDocumentLoadFailRef.current)) {
117-
onDocumentLoadFailRef.current();
118-
}
119-
}
120-
);
121-
});
122-
}, [file, withCredentials, cMapUrl, cMapPacked]);
117+
);
118+
}
119+
);
120+
}, [file, withCredentials, cMapUrl, cMapPacked, workerSrc]);
123121

124122
useEffect(() => {
125123
// draw a page of the pdf

0 commit comments

Comments
 (0)