ansu5555 / pdf-viewer-reactjs

A simple PDF viewer for React js
https://ansu5555.github.io/pdf-viewer-reactjs/
MIT License
140 stars 65 forks source link

[BUG] getMaxPageCount with useState #69

Open simon-baehler opened 3 years ago

simon-baehler commented 3 years ago

Hello,

I'm trying to set the number of pages using useState, but unfortunately, it's crashing.

Describe the bug I'm trying to use getMaxPageCount with useState

const [pages, setPages] = useState(0);
 <PDFViewer
    externalInput={true}
    document={{
        url: link,
    }}
    canvasCss='customCanvas'
    css='wrapperPDF'
    page={currentPage}
    getMaxPageCount={(pageCount) => setPages(pageCount)}
/>

but I've got this error on the console

react_devtools_backend.js:2430 Error while reading the pages ! TypeError: Cannot read property 'getPage' of null

Expected behavior the value of pages should best st to the number of pages

What will be awesome is to have a prop like onLoaded that takes a function how to allow us to do some stuff when the pdf was loaded whit success

Have a nice day, thank you for your help

ansu5555 commented 3 years ago

You have to call setPages after the PDFViewer component is mounted else it is rendering again while its getting rendered and throwing the error. Use it like below

import React, { useState, useEffect } from 'react' import PDFViewer from 'pdf-viewer-reactjs'

function App() {
  let pg = 0
  const [pages, setPages] = useState(0)

  useEffect(() => {
    setPages(pg)
  }, [pg])

  return (
    <>
      <PDFViewer
        externalInput={true}
        document={{
          url: link,
        }}
        canvasCss='customCanvas'
        css='wrapperPDF'
        page={currentPage}
        getMaxPageCount={(pageCount) => (pg = pageCount)}
      />

      <h1>{pages}</h1>
    </>
  )
}

export default App
devkf commented 3 years ago

Thanks for your answer

Not working for me :)

simon-baehler commented 3 years ago

Same, not working for me ;(

devkf commented 3 years ago

you can used this https://github.com/MGrin/mgr-pdf-viewer-react