Insert nodes into editor from and external editor state #4867
-
Imagine I have a lexical editor and an externally saved editor state which I want to insert at a specific place in the editor (replace an existing node with it, or just at the current selection). So what I tried to do is to extract the nodes from that external editor state and insert them before a specific node (let's sau node A): function insertNodes(editor: LexicalEditor, savedEditorState: SerializedEditorState) {
editor.update(() => {
const nodesToReplace = editor.parseEditorState(savedEditorState).read(() => {
const [maybeParagraph] = $getRoot().getChildren();
if (!$isParagraphNode(maybeParagraph)) {
return [];
}
return maybeParagraph.getChildren();
});
// this part is not important
// let's say I somehow get the right node before which to insert the new nodes
const nodeA = $getNodeByKey(key_of_node_a);
let target: LexicalNode | null = null;
nodesToReplace.forEach(node => {
const copy = $copyNode(node);
if (target === null) {
nodeA.insertBefore(copy, true);
} else {
target.insertAfter(copy, true);
}
target = copy;
});
});
} The problem is that I get errors like: How can I achieve this? Cheers. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
AFAICT, from Lexical's standpoint, you're in the same update callback, so scope shouldn't be an issue. I think the problem here is $copyNode. When you do this, you're basically cloning the nodes, but setting their key to null. Without a key, Lexical can't find the nodes in the EditorState, so it throws. Instead just don't copy these nodes - Lexical should assign them keys during parseEditorState. |
Beta Was this translation helpful? Give feedback.
-
Try this: $parseSerializedNode is better for when you don't want to deal with an entire editor state. |
Beta Was this translation helpful? Give feedback.
Try this:
https://codesandbox.io/s/lexical-inserting-nodes-forked-ryznvg?file=/src/plugins/InsertExternalNodesPlugin.js
$parseSerializedNode is better for when you don't want to deal with an entire editor state.