Show Chart from Previous Node if Data does not exist for the current node in React

53 Views Asked by At

I am currently working on implementing a chart which has different nodes (Network Chart).

Initially when the page is rendered, an API call is made which show network chart with different nodes. User can doublelick on Node and it will render a new chart for the selected Node. User can continue to click on nodes (parent -> child1 -> child2 -> child3). This is working fine.

In some scenarios, when a user double click a node, we do not have data from the API. In this case, we need to show error pop-up and also need to reload the chart with the previous node (parent node).

Here is the example of network chart looks like https://visjs.github.io/vis-network/examples/network/basicUsage.html

I am having difficulty in loading the previous node data when there is NO data from API call.

Here is pseudo code.

const NetworkGraph = (props: any) => {
  
  const container = useRef<HTMLInputElement | null>(null);
  const [nodeId, setNodeId] = useState(props.nodeId)
  const { graphData, isLoading } = useGetNetowrkGraphData(nodeId); //Custom hook making API call
  
  useEffect(() => {
    if (isLoading === false) {
      if (graphData.nodes.length <= 0) {
        setMessage('No data found', 'error');
        //TODO: Here I need to set the previous NodeId and show previous graph
      }

      const nodes = new DataSet(graphData.nodes);
      const edges = new DataSet(graphData.edges as any[]);
      const networkData = { nodes: nodes, edges: edges };

      const network = container.current && new Network(container.current, networkData, options);

      network?.on('doubleClick', function (params) {
        var ids = params.nodes;
        var clickedNodes = nodes.get(ids);

        if (clickedNodes && clickedNodes.length > 0) {
          setNodeId(clickedNodes[0].id);
        }
      });
    }
  }, [
    container,
    nodeId,
    graphData.nodes,
    graphData.edges,
    isLoading,
    setNodeId,
    setMessage,
  ]);

  if (isLoading) return <div>Loading...</div>;

  return (
    <>
      <Div>
          <div ref={container}/>
      </Div>
    </>
  );
};

export default NetworkGraph;
0

There are 0 best solutions below