Using instance.loadDocument() inside useEffect to open a file

PDF.js Express Version

Detailed description of issue
{User can select a PDF to view in the webViewer from the dropdown. The flow is much like the example provided here: https://pdfjs.express/documentation/samples/viewing, but implemented in ReactJs. When another file is selected an error is thrown: Unhandled Rejection (Error): Two instances of WebViewer were created on the same HTML element. Please create a new element for each instance of WebViewer.
What am I missing and how to fix it? }

Expected behaviour
{ Selected document should be loaded into WebViewer without any errors. }

Link to document
{Provide a link to the document in question if possible}

Code snippet
{
const viewer = useRef(null);

const [pdf, setPdf] = useState(undefined)

const docs = [

    {

        id: '0',

        text:'PDF-tron test',

        path: '/files/PDFTRON_about.pdf'

    },

    {

        id: '1',

        text:'ABY_PP_AR-5-0204',

        path: '/files/ABY_PP_AR-5-0204.pdf'

    },
]

let defaultFilePath = !!pdf ? docs.filter(x => {return x.id === pdf}) : docs[0]

useEffect(() => {

    WebViewer(

      {

        path: '/webviewer/lib',

        initialDoc: defaultFilePath.path,

      },

      viewer.current,

    ).then((instance) => {

        const file = docs.filter(x => {return x.id === pdf})

        

        if(file.length){

            console.log(file, file[0].path)

            instance.loadDocument(file[0].path);

        }

    });

}, [pdf] );

}

Hi,

Since your reference to pdf is changing, that useEffect hook is getting rerun which in turn is remounting WebViewer. You will have to pull that logic into it’s own useEffect.

const [instance, setInstance] = useState(null)
useEffect(() => {
   WebViewer(...).then(instance => {
       setInstance(instance)
   })
}, [])

useEffect(() => {
     if(instance && pdf) {
         instance.loadDocument(pdf)
     }
}, [pdf, instance])

I recommend taking a look at the React docs and learning the ins and outs of the dependecy arrays!

Thanks,
Logan

1 Like

Thanks a lot! :pray:

1 Like