Skip to content

Commit

Permalink
fix: orphaned nodes when parsing from Frame's children in strict mode (
Browse files Browse the repository at this point in the history
  • Loading branch information
prevwong authored Oct 4, 2023
1 parent f2b77fd commit 2fffe69
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 13 deletions.
5 changes: 5 additions & 0 deletions .changeset/old-chicken-lay.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@craftjs/core': patch
---

Fix orphaned nodes when parsing from Frame's children in strict mode
36 changes: 23 additions & 13 deletions packages/core/src/render/Frame.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,25 +44,35 @@ export const Frame: React.FC<React.PropsWithChildren<FrameProps>> = ({
initialData: data || json,
});

const isInitialChildrenLoadedRef = useRef(false);

useEffect(() => {
const { initialChildren, initialData } = initialState.current;

if (initialData) {
actions.history.ignore().deserialize(initialData);
} else if (initialChildren) {
const rootNode = React.Children.only(
initialChildren
) as React.ReactElement;

const node = query.parseReactElement(rootNode).toNodeTree((node, jsx) => {
if (jsx === rootNode) {
node.id = ROOT_NODE;
}
return node;
});

actions.history.ignore().addNodeTree(node);
return;
}

// Prevent recreating Nodes from child elements if we already did it the first time
// Usually an issue in React Strict Mode where this hook is called twice which results in orphaned Nodes
const isInitialChildrenLoaded = isInitialChildrenLoadedRef.current;

if (!initialChildren || isInitialChildrenLoaded) {
return;
}

const rootNode = React.Children.only(initialChildren) as React.ReactElement;

const node = query.parseReactElement(rootNode).toNodeTree((node, jsx) => {
if (jsx === rootNode) {
node.id = ROOT_NODE;
}
return node;
});

actions.history.ignore().addNodeTree(node);
isInitialChildrenLoadedRef.current = true;
}, [actions, query]);

return <RenderRootNode />;
Expand Down

0 comments on commit 2fffe69

Please sign in to comment.