xyflow / xyflow

React Flow | Svelte Flow - Powerful open source libraries for building node-based UIs with React (https://reactflow.dev) or Svelte (https://svelteflow.dev). Ready out-of-the-box and infinitely customizable.
https://xyflow.com
MIT License
21.54k stars 1.43k forks source link

Node gets unselected immediately after selecting. #4243

Open kevincrabbe opened 2 weeks ago

kevincrabbe commented 2 weeks ago

Describe the Bug

I have two components, Parent(Parent.tsx) and Child(Child.tsx). The Child component actually has the ReactFlow component:

export const Child = () => {
return (
    <div style={{ height: "700px", display: "flex" }}>
      <ReactFlow
        nodes={nodes}
        edges={edges}
        onNodesChange={onNodesChange}
        onEdgesChange={onEdgesChange}
        fitView
        nodeTypes={nodeTypes}
      >
        <Controls />
        <MiniMap />
        <Background variant={BackgroundVariant.Dots} gap={12} size={1} />
      </ReactFlow>
    </div>
  );
}

The Parent contains the Child but also needs to be aware of what node is selected in the Child:

export const Parent = () => {
const [selected, setSelected] = useState<string | null>(null);
  useOnSelectionChange({
    onChange: ({ nodes, edges }) => {
      const id = nodes
        .filter((node) => node.selected)
        .map((node) => node.id)[0];
setSelected(id)
    },
  });
return <Child/>
}

In App.tsx, parent is wrapped like this:

        <ReactFlowProvider>
          <Parent />
        </ReactFlowProvider>

When I selected a node, the node becomes selected and immediately unselected according to my logs. I know that this is because caused calling setSelected(id). When I remove that call, the node just stays selected after I click it. I don't see why this shouldn't work as it's not so different from the example here where selected nodes are kept track of: https://reactflow.dev/api-reference/hooks/use-on-selection-change. The parent component needs to know which node is selected in the child component.

Your Example Website or App

No response

Steps to Reproduce the Bug or Issue

  1. Create two components, a child and a parent
  2. Put the react flow component in the child
  3. Return the child component in the parent
  4. Wrap the parent with ReactFlowProvider
  5. Create some state in the parent `const [selected, setSelected] = useState<string | null>(null);
  6. Use useOnSelectionChange to call setSelected(id) when a node is selected
  7. Observe that the node gets selected and then immediately unselected

Expected behavior

I expected the node to get selected and to be able to track the id of which node is selected using useState but instead the node gets unselected when I call the state setter setSelected

Screenshots or Videos

No response

Platform

Additional context

No response

moklick commented 1 week ago

Could you create a codensadbox for this?

https://new.reactflow.dev