Search code examples
reactjsreact-hooksuse-effectuse-statereact-pdf

Dynamic file source React-PDF (Hooks)


I'm trying to implement a react-pdf solution in which the user can select which pdf they want to render. I have come up with a hooks solution but don't understand why the PDF is not rendering.


import React,{useState,useEffect} from  'react';
import samplePDF from "somelocalpath/microcert.pdf";
import file2 from "somelocalpath/CourseCertificate.pdf";
import { Document, Page,pdfjs } from 'react-pdf';
import './frontend.css';
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;

function Pdfview(){
  const [numPages, setNumPages] = useState(null);
  const [pageNumber, setPageNumber] = useState(1);
  const [pdfile,setPDF]=useState('');
  function onDocumentLoadSuccess({ numPages }) {
    setNumPages(numPages);
    setPageNumber(1);
    console.log(pdfile);
  }

  function changePage(offset) {
    setPageNumber(prevPageNumber => prevPageNumber + offset);
  }
  function changePDF(){
    setPDF({file2})
 }

  function previousPage() {
    changePage(-1);
  }

  function nextPage() {
    changePage(1);
  }
  useEffect(()=>{
  },[pdfile]);

  return(
  <div className='grid-container'>
    <div className='sidespace'></div>
      <div className='sidebar'>
        <button onClick={changePDF}>Click Here to Change PDF</button>
      </div>
        <div className='pdf'>
        <Document
        file={pdfile}
        onLoadSuccess={onDocumentLoadSuccess}
      >
        <Page pageNumber={pageNumber} />
      </Document>
      <div>
        <p>
          Page {pageNumber || (numPages ? 1 : '--')} of {numPages || '--'}
        </p>
        <button
          type="button"
          disabled={pageNumber <= 1}
          onClick={previousPage}
        >
          Previous
        </button>
        <button
          type="button"
          disabled={pageNumber >= numPages}
          onClick={nextPage}
        >
          Next
        </button>
      </div>
        </div>
        <div className='sidespaceright'></div>
  </div> 
);
}


export default Pdfview;

I know the PDF will render if I set the file equal to {samplePDF} or {file2} but I can't seem to figure out why it wont render if it's using pdfile from the useState hook. I get this error when trying to render it:

Error: Invalid parameter object: need either .data, .range or .url
    at _callee2$ (Document.js:332)
    at tryCatch (runtime.js:63)
    at Generator.invoke [as _invoke] (runtime.js:293)
    at Generator.next (runtime.js:118)
    at asyncGeneratorStep (asyncToGenerator.js:3)
    at _next (asyncToGenerator.js:25)
    at asyncToGenerator.js:32
    at new Promise (<anonymous>)
    at Document.findDocumentSource (asyncToGenerator.js:21)
    at _callee$ (Document.js:100)
    at tryCatch (runtime.js:63)
    at Generator.invoke [as _invoke] (runtime.js:293)
    at Generator.next (runtime.js:118)
    at asyncGeneratorStep (asyncToGenerator.js:3)
    at _next (asyncToGenerator.js:25)
    at asyncToGenerator.js:32
    at new Promise (<anonymous>)
    at Document.loadDocument (asyncToGenerator.js:21)
    at Document.componentDidUpdate (Document.js:388)
    at commitLifeCycles (react-dom.development.js:20684)
    at commitLayoutEffects (react-dom.development.js:23426)
    at HTMLUnknownElement.callCallback (react-dom.development.js:3945)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:3994)
    at invokeGuardedCallback (react-dom.development.js:4056)
    at commitRootImpl (react-dom.development.js:23151)
    at unstable_runWithPriority (scheduler.development.js:646)
    at runWithPriority$1 (react-dom.development.js:11276)
    at commitRoot (react-dom.development.js:22990)
    at performSyncWorkOnRoot (react-dom.development.js:22329)
    at react-dom.development.js:11327
    at unstable_runWithPriority (scheduler.development.js:646)
    at runWithPriority$1 (react-dom.development.js:11276)
    at flushSyncCallbackQueueImpl (react-dom.development.js:11322)
    at flushSyncCallbackQueue (react-dom.development.js:11309)
    at discreteUpdates$1 (react-dom.development.js:22420)
    at discreteUpdates (react-dom.development.js:3756)
    at dispatchDiscreteEvent (react-dom.development.js:5889)

Solution

  • I figured this out.

    Change function:

      function changePDF(){
        setPDF({file2})
     }
    

    to:

      function changePDF(){
        setPDF(file2)
     }