wojtekmaj / react-pdf

Display PDFs in your React app as easily as if they were images.
https://projects.wojtekmaj.pl/react-pdf
MIT License
9.11k stars 867 forks source link

Infinite re-renders with url prop #1658

Closed heyitaki closed 9 months ago

heyitaki commented 9 months ago

Before you start - checklist

Description

I'm running into an issue where the PDF is infinitely re-rendering if I try to set certain state in onLoadSuccess. I had a suspicion earlier that this was happening because of AWS presigned links, but the example below shows that this happens with public objects with permanent access links too.

1526 is potentially a related issue although I was able to reproduce this issue in 6.2.2 with the code below unlike OP.

Steps to reproduce

I have a minimal reproducible example below. Things render fine until the setPdf line is uncommented. I don't at all understand why this is triggering re-renders given that pdf isn't used anywhere. Note that this code works fine with local PDF files.

import { PDFDocumentProxy } from 'pdfjs-dist';
import { useState } from 'react';
import { Document, Page, pdfjs } from 'react-pdf';
import 'react-pdf/dist/Page/TextLayer.css';

pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.js`;

export const PdfViewer = () => {
  const [numPages, setNumPages] = useState(0);
  const [pdf, setPdf] = useState<PDFDocumentProxy | null>(null);

  return (
    <Document
      file={{
        url: 'https://public-pdfs-test.s3.amazonaws.com/table.pdf',
      }}
      onLoadSuccess={async (document) => {
        // setPdf(document);
        setNumPages(document.numPages);
      }}
    >
      {Array.from(new Array(numPages), (_el, idx) => (
        <Page
          key={`page_${idx + 1}`}
          pageNumber={idx + 1}
          renderAnnotationLayer={false}
          width={400}
        />
      ))}
    </Document>
  );
};

Expected behavior

Single render, pdf is set properly

Actual behavior

pdf is not set, PDF doesn't render and just shows Loading PDF... indefinitely.

Additional information

There are no errors in console (although previously I was seeing some Transport destroyed errors before I cut down the code to make a minimally reproducible example). A cursory glance at the network tab shows the worker is being called over and over: image

Environment

wojtekmaj commented 9 months ago
  1. Read the docs for using objects. https://github.com/wojtekmaj/react-pdf/blob/main/packages/react-pdf/README.md
  2. You don't need to use an object at all for such a simple case, just pass a string.