title: Fetching Async TreeView Data
body: <p>I'm new to react and I'm building a <code>TreeView</code> component in react where I fetch data as nodes are expanded. I'm using the TreeView from Material UI: <a href="https://material-ui.com/api/tree-view/" rel="nofollow noreferrer">https://material-ui.com/api/tree-view/</a></p>
  
  <p>I have created the component below which fetches data when a node is expanded. MyTreeItem is a custom version expanding the original with a fetch call. But I'm confused on how to display the childnodes. How can I do this? </p>
  
  <pre><code>import ReactDOM from "react-dom";
  import React from "react";
  import TreeView from "@material-ui/lab/TreeView";
  import ExpandMoreIcon from "@material-ui/icons/ExpandMore";
  import ChevronRightIcon from "@material-ui/icons/ChevronRight";
  import TreeItem from "@material-ui/lab/TreeItem";
  const { useState, useCallback } = React;
  
  export default function MyTreeItem({ id, name }) {
    const [childNodes, setChildNodes] = useState(null);
    const [expanded, setExpanded] = React.useState([]);
  
    function fakeAjax(url) {
      return fetch(url).then(res =&gt; {
        if (!res.ok) {
          throw new Error("HTTP error " + res.status);
        }
        return res.json();
      });
    }
  
    function fetchChildNodes(id) {
      // Should in reality be "URL/id", but fake JSON for now
      return fakeAjax(`https://api.myjson.com/bins/1aqhsc`);
    }
  
    const handleChange = (event, nodes) =&gt; {
      const expandingNodes = nodes.filter(x =&gt; !expanded.includes(x));
      setExpanded(nodes);
      if (expandingNodes[0]) {
        const childId = expandingNodes[0];
        fetchChildNodes(childId).then(result =&gt;
          setChildNodes(result.children.map(node =&gt; &lt;MyTreeItem {...node} /&gt;))
        );
      }
    };
  
    return (
      &lt;TreeView
        defaultCollapseIcon={&lt;ExpandMoreIcon /&gt;}
        defaultExpandIcon={&lt;ChevronRightIcon /&gt;}
        expanded={expanded}
        onNodeToggle={handleChange}
      &gt;
        {/*The node below should act as the root node for now */}
        &lt;TreeItem nodeId="1" label="Applications"&gt;
          {/*The childnodes should be here*/}
        &lt;/TreeItem&gt;
      &lt;/TreeView&gt;
    );
  }
  const rootElement = document.getElementById("root");
  ReactDOM.render(&lt;MyTreeItem /&gt;, rootElement);
  
  </code></pre>