Skip to content

Commit

Permalink
fix: ssr hydration error in strict mode
Browse files Browse the repository at this point in the history
  • Loading branch information
prevwong committed May 31, 2024
1 parent e99cafe commit cf1d4c0
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 148 deletions.
5 changes: 5 additions & 0 deletions .changeset/grumpy-shrimps-call.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@craftjs/core': patch
---

Fix <Element /> hydration errror in react strict mode
43 changes: 17 additions & 26 deletions packages/core/src/nodes/Element.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,42 +40,33 @@ export function Element<T extends React.ElementType>({
};

const { query, actions } = useInternalEditor();
const { node, inNodeContext } = useInternalNode((node) => ({
node: {
id: node.id,
data: node.data,
},
}));
const { id: nodeId, inNodeContext } = useInternalNode();

const [linkedNodeId] = useState<NodeId | null>(() => {
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;
});
Expand Down
122 changes: 0 additions & 122 deletions packages/core/src/nodes/tests/Element.test.tsx

This file was deleted.

0 comments on commit cf1d4c0

Please sign in to comment.