facebook / lexical

Lexical is an extensible text editor framework that provides excellent reliability, accessibility and performance.
https://lexical.dev
MIT License
19.47k stars 1.65k forks source link

Bug: Lexical editor tool not working on second time rendering #5842

Open alighazanfer opened 6 months ago

alighazanfer commented 6 months ago

I'm using lexical editor on next js 14. I used it for content writing purpose. I firstly get the data (content) in html from lexical and store it into my db through api's and then feteching data at onMount and painting it to lexical.

My FLOW: Lexical editor => HTML => DB DB => HTML =>Lexical editor

lexical version: "^0.14.2"

Code example:

const appendHtmlToEditor = (editor, HTMLContent) => {
    return editor?.update(() => {
      const TYPE = 'text/html';
      const parser = new DOMParser();
      const dom = parser.parseFromString(HTMLContent, TYPE);
      const nodes = $generateNodesFromDOM(editor, dom);
      $getRoot().select();
      $getRoot().clear();
      $insertNodes(nodes);
      setEditorState(JSON.stringify(nodes));
    });
  };

const OnChangePlugin = () => {
    const [editor] = useLexicalComposerContext();
    setActiveEditor(editor);

    const handleEditorOnChange = (listener) => {
      updatedContent.content = listener.editorState.read(() => $getRoot().getTextContent());

      editor.update(() => {
        const htmlString = $generateHtmlFromNodes(editor);
        updatedContent.htmlContent = htmlString;
      });

      !isEmpty(updatedContent) && handleDebounce( handleContentGenerationUpdate, updatedContent, content?.id);
    };

    useEffect(() => {
      return editor.registerUpdateListener((listener) => {
        handleEditorOnChange(listener);
      });
    }, [editor]);

    return null;
  };

useEffect(() => {
    appendHtmlToEditor(activeEditor, content?.htmlContent);
  }, [content, activeEditor]);

The current behavior and problem:

The editor tools (like bold, italic, etc.) are not working properly after navigating away from the editor page and returning back. The data is fetched and displayed in the editor, but the tools aren't functioning until you manually refresh the page. And this happened at second time. At first time all works fine but when I navigate to other compoentn and come again, The tools are not wokring but the data was paint.

Could you please help me to figour out this problme?

etrepum commented 6 months ago

If you post a full example of the problem (e.g. a repo that can run on stackblitz) where all of the code is present to reproduce and debug the issue, I can take a look