Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 140071

Mapping fetched data

$
0
0

I'm trying to build a TreeNode function in react that builds a tree structure of some data.

I have fake data as a starting point:

const fakeData = {
 "1234": {
   id: "1234",
   name: "Division",
   address: "string",
   childNodes: []
  }
};

When I expand the "Division" node with the "id" 1234, I want to fetch the children of this node. So my fakeData expands to something like this:

I'm using the fetch() method to get data, but I'm unsure of how to pass that data to resolve() method of the Promise. Right now I'm doing this:

function fakeAjax(url, id) {
  return new Promise((resolve, reject) => {
    fetch(url)
      .then(res => res.json())
      .then(result => {
        const nodes = result.map(node => node.id);
        resolve(fakeData[id].childNodes.map(nodes));
      });
  });
}

function fetchChildNodes(id) {
  return fakeAjax(`someUrl`, id);
}

function TreeNode({ id, name }) {
  const [childNodes, setChildNodes] = useState(null);

  // Toggle our display of child nodes
  const toggleExpanded = useCallback(() => {
      fetchChildNodes(id)
        .then(nodes => setChildNodes(nodes.map(node => <TreeNode {...node} />)))
    }
  }, [childNodes]);

But this is not passing the relavant data to the resolve method. Am I doing something wrong?


Viewing all articles
Browse latest Browse all 140071

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>