简体   繁体   中英

d3js Collapsible tree dynamic data from API not working

I am using this example along with ReactJS to draw a collapsible tree diagram. Example - https://bl.ocks.org/d3noob/43a860bc0024792f8803bba8ca0d5ecd . The problem I am facing is that my children are fetched from an API endpoint on click of the node rather than having it all at once since that might bring down the performance of the page. I have the treeData mentioned in the example in my state and after fetching the data from the API I am updating the state but how do I update the child node that is being clicked and show the fetched data. In the example since all data is already there the below method work perfectly fine.

    function click(d) {
// API call here and after fetching the data continue with the below code. The problem here is the state data is updated but I don't think the graph is updating along with that.
    if (d.children) {
        d._children = d.children;
        d.children = null;
      } else {
        d.children = d._children;
        d._children = null;
      }
    update(d);
  }

Can someone help me with this issue ? Thanks in advance.

It's hard to say since I don't have the api to test, but you need to combine new and old data, transform the data into a d3.hierarchy and add the ._children to the new nodes. This should be a start anyway.

function click(d) {
    // get your new data
    const new_data = await getData() // or whatever 
    
    // combine new data with old data, I'm assuming this will update treeData but I'm not sure
    d.children.push(new_data) 

    // call the hierarchy on new data so it has the mike magic it needs
    root = d3.hierarchy(treeData, di => di.children)

    // add the ._children attribute
    d.children.forEach(di => collapse)

    // continue as usual
    if (d.children) {
        d._children = d.children;
        d.children = null;
      } else {
        d.children = d._children;
        d._children = null;
      }
    update(d);
  }

I haven't tested this but it's where I would start.

** EDIT ** d.children.push(new_data) might not work. You might need to find the node the in the original treeData and add it to that nodes children, since d is already transformed by hierarchy.But if you can add it to d , that sounds easier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM