jpuri / react-draft-wysiwyg

A Wysiwyg editor build on top of ReactJS and DraftJS. https://jpuri.github.io/react-draft-wysiwyg
MIT License
6.38k stars 1.16k forks source link

Unhandled Runtime Error, Invariant Violation: Unknown DraftEntity key: null. #1405

Open SaadAli11 opened 8 months ago

SaadAli11 commented 8 months ago

https://ibb.co/nLGLS0n

Why does my React application using 'react-draft-wysiwyg' crash when I set an embedded link in the editor, resulting in an error like 'Invariant Violation: Unknown DraftEntity key: null'? How can I troubleshoot and resolve this issue? when i set the embedded link it not show any error but when i get the html again from the backend and set it to the editor it show error.

Here is my Code (check the useEffect that generate the error):

![error](https://github.com/jpuri/react-draft-wysiwyg/assets/89373992/ab5d4fdf-f918-406f-9a5c-afe6ba460545)

// ** React Imports
import React, {useEffect, useRef, useState} from 'react'

// ** Third Party Imports
import {EditorState, ContentState, convertFromHTML } from 'draft-js'
import {EditorWrapper} from "src/@core/styles/libs/react-draft-wysiwyg";
import ReactDraftWysiwyg from 'src/@core/components/react-draft-wysiwyg';
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import convertFromHTMLtoContentBlocks from 'draft-js'

interface MainProps {
  handle: any;
  setHandle: any;
}

const DescriptionTextEditorControlled = (props: MainProps) =>{

  const {handle,setHandle} = props

  const [editorState, setEditorState] = useState(EditorState.createEmpty());

  useEffect(() => {

    if (handle?.description !== null && handle?.description !== undefined) {

      const textToConvert = handle?.description;
      const blocksFromHTML = convertFromHTML(textToConvert);

      const contentState = ContentState.createFromBlockArray(blocksFromHTML.contentBlocks, blocksFromHTML.entityMap);

      setEditorState(EditorState.createWithContent(contentState));
    }
    else {
      // If handle.description is empty or undefined, clear the editor
      setEditorState(EditorState.createEmpty());
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const refEditor = useRef<HTMLDivElement | null>(null);

  const handleGetValue = () => {
    const htmlContent = refEditor.current;

    if(htmlContent){
      setHandle({...handle, description: htmlContent.innerHTML});
    }
  };

  const handleEditorRef = (ref: any) => {
    if (ref) {
      // Store the editor instance reference in the refEditor
      refEditor.current = ref;
    }
  };

  return (
    <EditorWrapper>
      <ReactDraftWysiwyg editorState={editorState} onEditorStateChange={setEditorState}  editorRef={handleEditorRef} onChange={handleGetValue}/>
    </EditorWrapper>
  );
}

export default DescriptionTextEditorControlled;
SaadAli11 commented 7 months ago

Screenshot_2