xp1632 / DFKI_working_log

0 stars 0 forks source link

global State and local variable: take treeData as example #16

Open xp1632 opened 1 year ago

xp1632 commented 1 year ago

image

We have two treeData in the code:

  1. The first one we use it in the useState, here we give an initial state of the treeData state variable, which is the treeData we get from nodeConfigs
  const [treeData, setTreeData] = useState<TreeItemData[]>(
    nodeConfigsToTreeData(nodeConfigRegistry.getAllNodeConfigs())
  );
  1. And inside the useEffect, we define a local variable treeData,
    • we pass this treeData also with nodeConfigsTreeData to our Filter function searchTreeDataWithHandleDataType
    • and update the treeData by the function's return value

- Here is quite essential, because before the searchTreeDataWithHandleDataType() has no return value - and the treeData we used in the filter function is the global 'treeData'


useEffect(() => {
    let treeData = nodeConfigsToTreeData(
      nodeConfigRegistry.getAllNodeConfigs()
    );
    if (startHandleInfo?.handleType && startHandleInfo?.handleDataType) {
      treeData = searchTreeDataWithHandleDataType(
        startHandleInfo.handleType,
        startHandleInfo?.handleDataType,
        treeData
      );
    }
    setTreeData(
      [...treeData, ...commandsToTreeData(commands)].sort(
        (a, b) => (a.rank ?? Infinity) - (b.rank ?? Infinity)
      )
    );
  }, [commands]);
xp1632 commented 1 year ago

image image