Repository navigation
Fix react-native-pdf throws undefined is not a function
#106351
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
mountiny
merged 4 commits into
Expensify:main
from
software-mansion-labs:fix/rn-pdf-crash
Nov 10, 2026
+356
−0
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
126 changes: 126 additions & 0 deletions
126
patches/react-native-pdf/react-native-pdf+7.0.2+007+fix-cancel-download-task.patch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,126 @@ | ||
| diff --git a/node_modules/react-native-pdf/index.js b/node_modules/react-native-pdf/index.js | ||
| --- a/node_modules/react-native-pdf/index.js | ||
| +++ b/node_modules/react-native-pdf/index.js | ||
| @@ -119,6 +119,8 @@ export default class Pdf extends Component { | ||
| }; | ||
|
|
||
| this.lastRNBFTask = null; | ||
| + // Goes up whenever a download starts or is canceled, so a download can tell it was replaced | ||
| + this._downloadId = 0; | ||
|
|
||
| } | ||
|
|
||
| @@ -128,15 +130,11 @@ export default class Pdf extends Component { | ||
| const curSource = Image.resolveAssetSource(prevProps.source); | ||
|
|
||
| if ((nextSource.uri !== curSource.uri)) { | ||
| - // if has download task, then cancel it. | ||
| - if (this.lastRNBFTask && this.lastRNBFTask.cancel) { | ||
| - this.lastRNBFTask.cancel(err => { | ||
| - this._loadFromSource(this.props.source); | ||
| - }); | ||
| - this.lastRNBFTask = null; | ||
| - } else { | ||
| - this._loadFromSource(this.props.source); | ||
| - } | ||
| + // Cancel the download of the previous source and load the new one right away. The canceled download | ||
| + // ignores its result, so there's no need to wait for the cancel callback, which react-native-blob-util | ||
| + // doesn't call when the request has already finished. | ||
| + this._cancelDownload(); | ||
| + this._loadFromSource(this.props.source); | ||
| } | ||
| } | ||
|
|
||
| @@ -167,10 +165,16 @@ export default class Pdf extends Component { | ||
| const filename = source.cacheFileName || SHA1(uri) + '.pdf'; | ||
| const cacheFile = ReactNativeBlobUtil.fs.dirs.CacheDir + '/' + filename; | ||
|
|
||
| + // The cache check is async, so the source can change before it ends. Only the latest source may load. | ||
| + const isCurrentSource = () => (Image.resolveAssetSource(this.props.source) || {}).uri === source.uri; | ||
| + | ||
| if (source.cache) { | ||
| ReactNativeBlobUtil.fs | ||
| .stat(cacheFile) | ||
| .then(stats => { | ||
| + if (!isCurrentSource()) { | ||
| + return; | ||
| + } | ||
| if (!Boolean(source.expiration) || (source.expiration * 1000 + stats.lastModified) > (new Date().getTime())) { | ||
| if (this._mounted) { | ||
| this.setState({path: cacheFile, isDownloaded: true}); | ||
| @@ -181,6 +185,9 @@ export default class Pdf extends Component { | ||
| } | ||
| }) | ||
| .catch(() => { | ||
| + if (!isCurrentSource()) { | ||
| + return; | ||
| + } | ||
| this._prepareFile(source); | ||
| }) | ||
|
|
||
| @@ -250,17 +257,30 @@ export default class Pdf extends Component { | ||
|
|
||
| }; | ||
|
|
||
| - _downloadFile = async (source, cacheFile) => { | ||
| - | ||
| - if (this.lastRNBFTask) { | ||
| - this.lastRNBFTask.cancel(err => { | ||
| + _cancelDownload = () => { | ||
| + // A download that is still running belongs to a source that is no longer wanted | ||
| + this._downloadId += 1; | ||
| + const task = this.lastRNBFTask; | ||
| + this.lastRNBFTask = null; | ||
| + if (task && typeof task.cancel === 'function') { | ||
| + task.cancel(err => { | ||
| }); | ||
| - this.lastRNBFTask = null; | ||
| } | ||
| + }; | ||
| + | ||
| + _downloadFile = async (source, cacheFile) => { | ||
| + | ||
| + // Only one download runs at a time | ||
| + this._cancelDownload(); | ||
| + const downloadId = this._downloadId; | ||
| + // False once this download was canceled or a newer one started. Its result is then ignored: canceling | ||
| + // rejects the task, which isn't an error to report, and a replaced download must not show its file. | ||
| + const isCurrentDownload = () => this._downloadId === downloadId; | ||
|
|
||
| const tempCacheFile = cacheFile + '.tmp'; | ||
| this._unlinkFile(tempCacheFile); | ||
|
|
||
| + // Store the task itself, which has cancel(). The promise that catch() returned, stored here before, doesn't. | ||
| this.lastRNBFTask = ReactNativeBlobUtil.config({ | ||
| // response data will be saved to this path if it has access right. | ||
| path: tempCacheFile, | ||
| @@ -278,9 +298,6 @@ export default class Pdf extends Component { | ||
| if (this._mounted) { | ||
| this.setState({progress: received / total}); | ||
| } | ||
| - }) | ||
| - .catch(async (error) => { | ||
| - this._onError(error); | ||
| }); | ||
|
|
||
| this.lastRNBFTask | ||
| @@ -313,6 +330,9 @@ export default class Pdf extends Component { | ||
| ReactNativeBlobUtil.fs | ||
| .cp(tempCacheFile, cacheFile) | ||
| .then(() => { | ||
| + if (!isCurrentDownload()) { | ||
| + return; | ||
| + } | ||
| if (this._mounted) { | ||
| this.setState({path: cacheFile, isDownloaded: true, progress: 1}); | ||
| } | ||
| @@ -323,6 +343,9 @@ export default class Pdf extends Component { | ||
| }); | ||
| }) | ||
| .catch(async (error) => { | ||
| + if (!isCurrentDownload()) { | ||
|
mountiny marked this conversation as resolved.
Resolved
|
||
| + return; | ||
| + } | ||
| this._unlinkFile(tempCacheFile); | ||
| this._unlinkFile(cacheFile); | ||
| this._onError(error); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,213 @@ | ||
| // cspell:ignore RNBF RNPDF | ||
| /** | ||
| * Runs the real react-native-pdf JS (node_modules/react-native-pdf/index.js, with our patches) with react-native-blob-util | ||
| * mocked. NativePDFViewTest mocks react-native-pdf out, so it can't catch problems in the library's own download code. | ||
| * | ||
| * Regression tests for https://github.com/Expensify/App/issues/106338: changing the PDF source while a download was | ||
| * running threw "undefined is not a function" from `lastRNBFTask.cancel()` as an unhandled promise rejection. | ||
| */ | ||
| import {render, screen} from '@testing-library/react-native'; | ||
|
|
||
| import {createHash} from 'crypto'; | ||
| import React from 'react'; | ||
| import Pdf from 'react-native-pdf'; | ||
|
|
||
| import waitForBatchedUpdatesWithAct from '../utils/waitForBatchedUpdatesWithAct'; | ||
|
|
||
| type MockResponse = {respInfo: {headers: Record<string, string>}}; | ||
|
|
||
| type MockTask = Promise<MockResponse> & { | ||
| uri: string; | ||
| isCanceled: boolean; | ||
| cancel: jest.Mock; | ||
| progress: () => MockTask; | ||
| finish: () => void; | ||
| fail: (error: Error) => void; | ||
| }; | ||
|
|
||
| const mockTasks: MockTask[] = []; | ||
| const mockCachedFiles = new Set<string>(); | ||
| // Cache checks wait for this before they settle, so a test can change the source while one is running | ||
| let mockCacheCheckGate: Promise<void> = Promise.resolve(); | ||
|
|
||
| jest.mock('react-native-blob-util', () => { | ||
| const createTask = (uri: string): MockTask => { | ||
| let resolveTask: (response: MockResponse) => void = () => {}; | ||
| let rejectTask: (reason: unknown) => void = () => {}; | ||
| let isSettled = false; | ||
| const promise = new Promise<MockResponse>((resolve, reject) => { | ||
| resolveTask = resolve; | ||
| rejectTask = reject; | ||
| }); | ||
|
|
||
| const task: MockTask = Object.assign(promise, { | ||
| uri, | ||
| isCanceled: false, | ||
| progress: () => task, | ||
| // Like react-native-blob-util: cancel() rejects the task, and once the task has settled it's a no-op that | ||
| // never calls its callback | ||
| cancel: jest.fn((callback?: (error: unknown) => void) => { | ||
| if (isSettled) { | ||
| return; | ||
| } | ||
| isSettled = true; | ||
| task.isCanceled = true; | ||
| rejectTask(new Error('canceled')); | ||
| callback?.(null); | ||
| }), | ||
| finish: () => { | ||
| isSettled = true; | ||
| resolveTask({respInfo: {headers: {}}}); | ||
| }, | ||
| fail: (error: Error) => { | ||
| isSettled = true; | ||
| rejectTask(error); | ||
| }, | ||
| }); | ||
| mockTasks.push(task); | ||
| return task; | ||
| }; | ||
|
|
||
| return { | ||
| __esModule: true, | ||
| default: { | ||
| config: () => ({fetch: (_method: string, uri: string) => createTask(uri)}), | ||
| fs: { | ||
| dirs: {CacheDir: '/cache'}, | ||
| stat: jest.fn((path: string) => mockCacheCheckGate.then(() => (mockCachedFiles.has(path) ? {lastModified: Date.now()} : Promise.reject(new Error('not cached'))))), | ||
| unlink: jest.fn(() => Promise.resolve()), | ||
| cp: jest.fn(() => Promise.resolve()), | ||
| }, | ||
| }, | ||
| }; | ||
| }); | ||
|
|
||
| jest.mock('react-native-pdf/fabric/RNPDFPdfNativeComponent', () => ({__esModule: true, default: 'RNPDFPdfView', Commands: {}})); | ||
| jest.mock('react-native-pdf/PdfView', () => () => null); | ||
|
|
||
| type PdfInternals = { | ||
| state: {path: string; isDownloaded: boolean}; | ||
| // eslint-disable-next-line @typescript-eslint/naming-convention -- react-native-pdf's own method name | ||
| _downloadFile: (...args: unknown[]) => Promise<void>; | ||
| }; | ||
|
|
||
| function isPdfInternals(instance: unknown): instance is PdfInternals { | ||
| return typeof instance === 'object' && instance !== null && 'state' in instance && '_downloadFile' in instance; | ||
| } | ||
|
|
||
| const URL_WITH_OLD_TOKEN = 'https://www.expensify.com/receipts/w_1.pdf?encryptedAuthToken=old'; | ||
| const URL_WITH_NEW_TOKEN = 'https://www.expensify.com/receipts/w_1.pdf?encryptedAuthToken=new'; | ||
|
|
||
| // react-native-pdf names the cache file after the SHA-1 of the URI | ||
| const getCacheFile = (uri: string) => `/cache/${createHash('sha1').update(uri).digest('hex')}.pdf`; | ||
|
|
||
| function renderPdf(uri: string, onError: jest.Mock) { | ||
| const renderWithSource = (sourceURI: string) => ( | ||
| source={{uri: sourceURI, cache: true, expiration: 864000}} | ||
| onError={onError} | ||
| /> | ||
| ); | ||
| const {rerender} = render(renderWithSource(uri)); | ||
| const pdf: unknown = screen.UNSAFE_getByType(Pdf).instance; | ||
| if (!isPdfInternals(pdf)) { | ||
| throw new Error('Expected the react-native-pdf component instance'); | ||
| } | ||
|
|
||
| // The library doesn't await _downloadFile, so in the app a rejection from it is an unhandled promise rejection | ||
| const escapedRejections: unknown[] = []; | ||
| const {_downloadFile: downloadFile} = pdf; | ||
| jest.spyOn(pdf, '_downloadFile').mockImplementation((...args) => { | ||
| const download = downloadFile(...args); | ||
| download.catch((error: unknown) => escapedRejections.push(error)); | ||
| return download; | ||
| }); | ||
|
|
||
| return {pdf, escapedRejections, changeSource: (nextURI: string) => rerender(renderWithSource(nextURI))}; | ||
| } | ||
|
|
||
| describe('react-native-pdf download cancellation', () => { | ||
| beforeEach(() => { | ||
| mockTasks.length = 0; | ||
| mockCachedFiles.clear(); | ||
| mockCacheCheckGate = Promise.resolve(); | ||
| }); | ||
|
|
||
| it('cancels the old download and shows the new source when the source changes during a download', async () => { | ||
| // Given a PDF whose download is still running | ||
| const onError = jest.fn(); | ||
| const {pdf, escapedRejections, changeSource} = renderPdf(URL_WITH_OLD_TOKEN, onError); | ||
| await waitForBatchedUpdatesWithAct(); | ||
|
|
||
| // When the auth token in its URL is refreshed and the new download finishes | ||
| changeSource(URL_WITH_NEW_TOKEN); | ||
| await waitForBatchedUpdatesWithAct(); | ||
| mockTasks.at(1)?.finish(); | ||
| await waitForBatchedUpdatesWithAct(); | ||
|
|
||
| // Then the old download is canceled without an error and the new one is shown | ||
| expect(mockTasks.map((task) => task.uri)).toEqual([URL_WITH_OLD_TOKEN, URL_WITH_NEW_TOKEN]); | ||
| expect(mockTasks.at(0)?.isCanceled).toBe(true); | ||
| expect(escapedRejections).toEqual([]); | ||
| expect(onError).not.toHaveBeenCalled(); | ||
| expect(pdf.state).toMatchObject({path: getCacheFile(URL_WITH_NEW_TOKEN), isDownloaded: true}); | ||
| }); | ||
|
|
||
| it('ignores a download that finished just before the source changed', async () => { | ||
| // Given a PDF whose download finishes right when its source changes to one that's already cached | ||
| const onError = jest.fn(); | ||
| const {pdf, escapedRejections, changeSource} = renderPdf(URL_WITH_OLD_TOKEN, onError); | ||
| await waitForBatchedUpdatesWithAct(); | ||
| mockCachedFiles.add(getCacheFile(URL_WITH_NEW_TOKEN)); | ||
|
|
||
| // When the finished download is handled after the source changed | ||
| mockTasks.at(0)?.finish(); | ||
| changeSource(URL_WITH_NEW_TOKEN); | ||
| await waitForBatchedUpdatesWithAct(); | ||
|
|
||
| // Then the new source stays shown | ||
| expect(escapedRejections).toEqual([]); | ||
| expect(onError).not.toHaveBeenCalled(); | ||
| expect(pdf.state).toMatchObject({path: getCacheFile(URL_WITH_NEW_TOKEN), isDownloaded: true}); | ||
| }); | ||
|
|
||
| it('ignores a cache check that finishes after the source changed', async () => { | ||
| // Given a PDF whose cache check is still running | ||
| let finishCacheChecks: () => void = () => {}; | ||
| mockCacheCheckGate = new Promise((resolve) => { | ||
| finishCacheChecks = resolve; | ||
| }); | ||
| const onError = jest.fn(); | ||
| const {pdf, escapedRejections, changeSource} = renderPdf(URL_WITH_OLD_TOKEN, onError); | ||
|
|
||
| // When the source changes to a cached file before that check ends | ||
| mockCachedFiles.add(getCacheFile(URL_WITH_NEW_TOKEN)); | ||
| changeSource(URL_WITH_NEW_TOKEN); | ||
| finishCacheChecks(); | ||
| await waitForBatchedUpdatesWithAct(); | ||
|
|
||
| // Then the old source isn't downloaded and the new one is shown | ||
| expect(mockTasks).toHaveLength(0); | ||
| expect(escapedRejections).toEqual([]); | ||
| expect(onError).not.toHaveBeenCalled(); | ||
| expect(pdf.state).toMatchObject({path: getCacheFile(URL_WITH_NEW_TOKEN), isDownloaded: true}); | ||
| }); | ||
|
|
||
| it('reports a failed download once', async () => { | ||
| // Given a PDF whose download is running | ||
| const onError = jest.fn(); | ||
| const {pdf, escapedRejections} = renderPdf(URL_WITH_NEW_TOKEN, onError); | ||
| await waitForBatchedUpdatesWithAct(); | ||
|
|
||
| // When the download fails | ||
| const networkError = new Error('network failure'); | ||
| mockTasks.at(0)?.fail(networkError); | ||
| await waitForBatchedUpdatesWithAct(); | ||
|
|
||
| // Then the error is reported once and nothing is shown as downloaded | ||
| expect(onError).toHaveBeenCalledTimes(1); | ||
| expect(onError).toHaveBeenCalledWith(networkError); | ||
| expect(pdf.state.isDownloaded).toBe(false); | ||
| expect(escapedRejections).toEqual([]); | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
NAB: wonday/react-native-pdf#1057 also ignores a cache
stat()in_loadFromSourcethat settles after the source changed (isCurrentSource), but this patch doesn't