Skip to content

Commit 2fffe69

Browse files
authored
fix: orphaned nodes when parsing from Frame's children in strict mode (#567)
1 parent f2b77fd commit 2fffe69

File tree

2 files changed

+28
-13
lines changed

2 files changed

+28
-13
lines changed

.changeset/old-chicken-lay.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@craftjs/core': patch
3+
---
4+
5+
Fix orphaned nodes when parsing from Frame's children in strict mode

packages/core/src/render/Frame.tsx

+23-13
Original file line numberDiff line numberDiff line change
@@ -44,25 +44,35 @@ export const Frame: React.FC<React.PropsWithChildren<FrameProps>> = ({
4444
initialData: data || json,
4545
});
4646

47+
const isInitialChildrenLoadedRef = useRef(false);
48+
4749
useEffect(() => {
4850
const { initialChildren, initialData } = initialState.current;
4951

5052
if (initialData) {
5153
actions.history.ignore().deserialize(initialData);
52-
} else if (initialChildren) {
53-
const rootNode = React.Children.only(
54-
initialChildren
55-
) as React.ReactElement;
56-
57-
const node = query.parseReactElement(rootNode).toNodeTree((node, jsx) => {
58-
if (jsx === rootNode) {
59-
node.id = ROOT_NODE;
60-
}
61-
return node;
62-
});
63-
64-
actions.history.ignore().addNodeTree(node);
54+
return;
55+
}
56+
57+
// Prevent recreating Nodes from child elements if we already did it the first time
58+
// Usually an issue in React Strict Mode where this hook is called twice which results in orphaned Nodes
59+
const isInitialChildrenLoaded = isInitialChildrenLoadedRef.current;
60+
61+
if (!initialChildren || isInitialChildrenLoaded) {
62+
return;
6563
}
64+
65+
const rootNode = React.Children.only(initialChildren) as React.ReactElement;
66+
67+
const node = query.parseReactElement(rootNode).toNodeTree((node, jsx) => {
68+
if (jsx === rootNode) {
69+
node.id = ROOT_NODE;
70+
}
71+
return node;
72+
});
73+
74+
actions.history.ignore().addNodeTree(node);
75+
isInitialChildrenLoadedRef.current = true;
6676
}, [actions, query]);
6777

6878
return <RenderRootNode />;

0 commit comments

Comments
 (0)