#How to update the value inside the data passed to a Node

1 messages · Page 1 of 1 (latest)

woven crystal
#

I want to change the value of a variable that is passed inside the data object when creating a node

const node = [
          {
            id: '1',
            position: { x: 100, y: 350 },
            type: 'NeighborSelector',
            data: {
              values: res.filter(val => val?.policyDisabled === null),
              img: cloudzone,
              placeholder: 'Please Selet a Zone',
              totalIds: 1,
              isZone: true,
              selectedValue: ''
            },
          },
setNodes(node);

I want to perform this action in the onChange callback function of that very own node

#

The node is a Select so I want the selected value to be reflected by the selectedValue variable which is triggered by the onChange event

#

How to update the value inside the data passed to a Node

vernal trout
#

Same way you would update any other property of a node

#
setNodes(nodes => nodes.map(node => {
  if (node.id === nodeId) {
    return { ...node, data: { ...node.data, selectedValue: nextValue }
  }

  return node
})
woven crystal
woven crystal
#
  const [nodes, setNodes, onNodesChange] = useNodesState();


  const handleNodesChange = useCallback(
    (changes) => {
      onNodesChange(changes);

      // Check if all NeighborSelector nodes have selected values
      const neighborSelectors = nodes.filter((node) => node.type === 'NeighborSelector');
      const allSelected = neighborSelectors.every((node) => node.data.selectedValue !== '');

      if (nodes.length > 1 && allSelected) {
        console.log('All NeighborSelector nodes have selected values:', allSelected);
        // Execute the logic when the condition is met
        console.log("Found the black sheep 2");
      }
    },
    [nodes, onNodesChange]
  );


<ReactFlow
...
onNodesChange={handleNodesChange}
            >
#

Am I doing something wrong here?

vernal trout
#

The error has a link, click on it and you'll be taken to the Troubleshooting page that explains the error.

woven crystal
#

Now I am getting this error

vernal trout
#

You aren't passing any initial nodes to useNodesState();

#

At least pass an empty array if you have no initial nodes