Skip to content
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

Fix backward compatibility for usePDF hook #2334

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions packages/renderer/src/dom/usePDF.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,19 @@ import { useState, useRef, useEffect, useCallback } from 'react';

import { pdf } from '../index';

const useCommittedRef = value => {
const ref = useRef();

useEffect(() => {
ref.current = value;
});

return ref;
};

export const usePDF = ({ document } = {}) => {
const pdfInstance = useRef(null);
const committedDocument = useCommittedRef(document);

const [state, setState] = useState({
url: null,
Expand Down Expand Up @@ -65,8 +76,15 @@ export const usePDF = ({ document } = {}) => {
};
}, [state.url]);

const update = useCallback(newDoc => {
pdfInstance.current.updateContainer(newDoc);
// make update function stable
const update = useCallback((...args) => {
if (args.length === 0) {
// TODO: add warning that no args update would be removed in next versions
pdfInstance.current.updateContainer(committedDocument.current);
} else {
const [newDoc] = args;
pdfInstance.current.updateContainer(newDoc);
}
}, []);

return [state, update];
Expand Down
25 changes: 25 additions & 0 deletions packages/renderer/tests/usePDF.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
*/

/* eslint-disable import/no-extraneous-dependencies */
import { useEffect, useState } from 'react';
import { renderHook, waitFor, act } from '@testing-library/react';
import { usePDF, Document, Page, Text } from '../src/dom';

Expand Down Expand Up @@ -57,3 +58,27 @@ it('updates document', async () => {

expect(result.current[0].blob.size).not.toEqual(pdfSize);
});

it('backward compatible with previous hook', async () => {
const { result } = renderHook(() => {
const [document, setDoc] = useState(() => <TestDocument />);
const [instance, update] = usePDF({ document });

useEffect(update, [document]);

return [
instance,
() => setDoc(<TestDocument title="Long long long title" />),
];
});

await waitFor(() => expect(result.current[0].loading).toBeFalsy());

const pdfSize = result.current[0].blob.size;

act(() => result.current[1]());

await waitFor(() => expect(result.current[0].loading).toBeFalsy());

expect(result.current[0].blob.size).not.toEqual(pdfSize);
});