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?