Wednesday, 1 January 2020

Appending fetched data

I'm trying to build a treeview component in react where data for the tree is fetched based on the nodes expanded by the user.

Problem

I want to replace the code inside handleChange with data from my server, so that I append the data i fetch to the tree state. How can I achieve this with react?

The data i get can look like this:

{
  "children": [
    {
      "id": "2212",
      "parentId": "3321",
      "name": "R&D",
      "address": "homestreet"
    },
    {
      "id": "4212",
      "parentId": "3321",
      "name": "Testing",
      "address": "homestreet"
    }
  ]
}

My Code

import React, { useState } from "react";
import { makeStyles } from "@material-ui/core/styles";
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 useStyles = makeStyles({
  root: {
    height: 216,
    flexGrow: 1,
    maxWidth: 400
  }
});

export default function FileSystemNavigator() {
  const classes = useStyles();

  const initialData = {
    root: [
      {
        id: "1",
        label: "Applications"
      }
    ],
  };

  const [tree, setTree] = useState(initialData);

  const handleChange = (event, nodeId) => {
    setTimeout(() => {
      const newTree = {
        ...tree,
        [nodeId]: [
          {
            id: "2",
            label: "Calendar"
          },
          {
            id: "3",
            label: "Settings"
          },
          {
            id: "4",
            label: "Music"
          }
        ]
      };

      setTree(newTree);
    }, 1000); // simulate xhr
  };

  const renderTree = children => {
    return children.map(child => {
      const childrenNodes =
        tree[child.id] && tree[child.id].length > 0
          ? renderTree(tree[child.id])
          : [<div />];

      return (
        <TreeItem key={child.id} nodeId={child.id} label={child.label}>
          {childrenNodes}
        </TreeItem>
      );
    });
  };

  return (
    <TreeView
      className={classes.root}
      defaultCollapseIcon={<ExpandMoreIcon />}
      defaultExpandIcon={<ChevronRightIcon />}
      onNodeToggle={handleChange}
    >
      {renderTree(tree.root)}
    </TreeView>
  );
}



from Appending fetched data

No comments:

Post a Comment