muntun
muntun

Reputation: 85

pdftron react typscript next Error: Two instances of WebViewer were created on the same HTML element

i'm trying to use pdftron from apryse docx editor i can use the docx editor normally but i keep getting error like the image bellow

error from page view detailed error preview

these are my code

wordeditor.tsx

"use client";
import { useEffect, useRef } from "react";
import WebViewer from "@pdftron/webviewer";
// const WebViewer = dynamic((): any => import('@pdftron/webviewer'), {ssr: false});

const licenseKey =
  "";

const WordEditor = () => {
  const viewerDiv = useRef<any>(null);

  useEffect(() => {
    WebViewer(
      {
        path: "/webviewer/lib",
        licenseKey: licenseKey,
        initialDoc:
          "https://pdftron.s3.amazonaws.com/downloads/pl/legal-contract.docx",
        enableOfficeEditing: true,
      },
      viewerDiv.current
    ).then((instance) => {
      const { documentViewer } = instance.Core;
      // you can now call WebViewer APIs here...
    });
  }, []);

  return (
    <div className="webviewer" ref={viewerDiv} style={{ height: "100%" }}></div>
  );
};

export default WordEditor;

and then insert it as a component in my page.tsx

import dynamic from 'next/dynamic';
const WebViewer = dynamic((): any => import('./wordeditor'), {ssr: false});

const WordEditor = () => {

    return (
        <div className='w-full h-full'>
            <WebViewer/>
        </div>
    );
}

export default WordEditor;

can anyone help me with this error? i have tried search in other questions but i still cannot fix this error especially in react typescript next js

as for package i use

thanks before.

Upvotes: 0

Views: 469

Answers (2)

Roger
Roger

Reputation: 1

The issue is most likely due to a change in React 18 which results in useEffect being called twice in development builds. You can read more about this in https://apryse.com/blog/two-instances-of-webviewer-warning-and-fix

Upvotes: 0

muntun
muntun

Reputation: 85

update. i solved it by change WebViewer promise to Asynchronous and it work here's the code to change it to Asynchronous :

"use client";
import { useEffect, useRef } from "react";
import WebViewer from "@pdftron/webviewer";

const licenseKey =
  "";

const WordEditor = () => {
  const viewer = useRef<any>(null);

  useEffect(() => {
    const callView = async () => {
      try {
        const docx = await WebViewer(
          {
            path: "/webviewer/lib",
            licenseKey: licenseKey,
            enableOfficeEditing: true,
          },
          viewer.current
        )
        const { Core, UI } = docx;
        const { documentViewer, annotationManager, Annotations, Tools } = Core;
      } catch (error) {
        console.log('viewer error ==> ', error)
      }
    }
    callView()
  }, []);

  return (
    <div id="viewer" className="webviewer" ref={viewer} style={{ height: "100%" }}></div>
  );
};

Cheers!

Upvotes: 0

Related Questions