From be8ff499be3b12f21b1ce295cdc1cc760c7c2fa5 Mon Sep 17 00:00:00 2001 From: Prev Wong Date: Fri, 31 May 2024 11:17:33 +0800 Subject: [PATCH] fix: ssr hydration error in strict mode --- .changeset/grumpy-shrimps-call.md | 5 ++++ packages/core/src/nodes/Element.tsx | 43 ++++++++++++----------------- 2 files changed, 22 insertions(+), 26 deletions(-) create mode 100644 .changeset/grumpy-shrimps-call.md diff --git a/.changeset/grumpy-shrimps-call.md b/.changeset/grumpy-shrimps-call.md new file mode 100644 index 000000000..3471cf5fc --- /dev/null +++ b/.changeset/grumpy-shrimps-call.md @@ -0,0 +1,5 @@ +--- +'@craftjs/core': patch +--- + +Fix hydration errror in react strict mode diff --git a/packages/core/src/nodes/Element.tsx b/packages/core/src/nodes/Element.tsx index 8db7f4f6e..22b369e1f 100644 --- a/packages/core/src/nodes/Element.tsx +++ b/packages/core/src/nodes/Element.tsx @@ -40,42 +40,33 @@ export function Element({ }; const { query, actions } = useInternalEditor(); - const { node, inNodeContext } = useInternalNode((node) => ({ - node: { - id: node.id, - data: node.data, - }, - })); + const { id: nodeId, inNodeContext } = useInternalNode(); const [linkedNodeId] = useState(() => { invariant(!!id, ERROR_TOP_LEVEL_ELEMENT_NO_ID); - const { id: nodeId, data } = node; + const node = query.node(nodeId).get(); if (inNodeContext) { - let linkedNodeId; - - const existingNode = - data.linkedNodes && - data.linkedNodes[id] && - query.node(data.linkedNodes[id]).get(); + const existingNode = node.data.linkedNodes[id] + ? query.node(node.data.linkedNodes[id]).get() + : null; // Render existing linked Node if it already exists (and is the same type as the JSX) if (existingNode && existingNode.data.type === is) { - linkedNodeId = existingNode.id; - } else { - // otherwise, create and render a new linked Node - const linkedElement = React.createElement( - Element, - elementProps, - children - ); + return existingNode.id; + } - const tree = query.parseReactElement(linkedElement).toNodeTree(); + // otherwise, create and render a new linked Node + const linkedElement = React.createElement( + Element, + elementProps, + children + ); - linkedNodeId = tree.rootNodeId; - actions.history.ignore().addLinkedNodeFromTree(tree, nodeId, id); - } - return linkedNodeId; + const tree = query.parseReactElement(linkedElement).toNodeTree(); + + actions.history.ignore().addLinkedNodeFromTree(tree, nodeId, id); + return tree.rootNodeId; } return null; });