Please add a fetch API data example - UseEffect
leonardorodd opened this issue · 2 comments
I've tried several ways, but the same id error always occurs when trying to access the component's state: Error not detected: Unable to add item: item with id 1 already exists
import React, { useState, useEffect } from 'react';
import Graph from 'react-graph-vis';
import { toast } from 'react-toastify';
import cloneDeep from 'lodash/cloneDeep';
import { v4 as uuidv4 } from 'uuid';
import server from '../../../../../../assets/images/server.png';
import switch_ from '../../../../../../assets/images/switch.png';
import vmUp from '../../../../../../assets/images/vm_up.png';
import vmDown from '../../../../../../assets/images/vm_down.png';
import vmBooting from '../../../../../../assets/images/vm_booting.png';
import apiClient from '../../../../../../services/apiClient';
const graph = {
nodes: [{ id: 0, label: 'Node 1', title: 'node 1 tootip text' }],
edges: [{ from: 0, to: 0 }],
};
export default function App({ sliceUrn }) {
const [graphData, setGraphData] = useState(graph);
const [graphKey, setGraphKey] = useState(uuidv4);
const options = {
layout: {
hierarchical: true,
},
edges: {
color: '#000000',
},
height: '500px',
};
function generateGraphData(topology) {
const newGraph = cloneDeep(graphData);
topology.full_topology.nodes.forEach(node => {
const newNodeId = Math.max(...newGraph.nodes.map(d => d.id)) + 1;
const newNode = {
id: newNodeId,
shape: 'image',
label: `Node ${newNodeId}`,
title: `node ${newNodeId} tootip text dd`,
img: () => {
if (node.resource_type === 'virtual_machine') {
if (node.status === 'UP_AND_READY') {
return vmUp;
}
if (node.status === 'SHOOTING_DOWN') {
return vmDown;
}
if (
node.status === 'DOWN' ||
node.status === 'SHOOTING_DOWN'
) {
return '';
}
return vmBooting;
}
if (node.resource_type === 'node') {
return server;
}
return switch_;
},
};
newGraph.nodes.push(newNode);
});
newGraph.nodes.shift();
return newGraph;
}
useEffect(() => {
apiClient
.get(`/slices/${sliceUrn}/topology`)
.then(response => {
setGraphData(generateGraphData(response));
})
.catch(error => toast.error(error.message));
}, []);
console.log(graphData);
return (
<div className="App">
<button
type="button"
onClick={() => setGraphData(cloneDeep(graph))}
>
Back to Original
</button>
<Graph key={graphKey} graph={graphData} options={options} />
</div>
);
}
...