I've taken the example of 'react-d3-graph' at :
I'm attempting to render the Graph component within the 'react-d3-graph' working with non hardcoded data by reading data from a file using fetch.
But when I read the data from a file via a fetch() and assign the data read from the file to component I get these messages in the console and nothing is displayed.
react-d3-graph :: Graph : you have not provided enough data for react-d3-graph to render something. You need to provide at least one node
react-d3-graph :: Graph :: you are passing invalid data to react-d3-graph. You must include a links array, even if empty, in the data object you're passing down to the component.
This message is displayed before the console output of the data read in from the file so it's a timing issue. I've tried reading around but can't find a way round this.
Can anyone please help. Thanks.
import React, { Component } from 'react'
import { Graph } from "react-d3-graph";
class GraphView extends Component {
constructor(props) {
super(props)
this.state = {
data : {}
}
}
componentDidMount() {
fetch("http://10.10.1.185:4200/chartdata.txt")
.then((r) => r.text())
.then(text => {
console.log("text=" + text);
this.state.data = text
console.log("this.state.data=" + this.state.data)
})
}
render() {
const myConfig = {
nodeHighlightBehavior: true,
node: {
color: "lightgreen",
size: 200,
highlightStrokeColor: "blue",
},
link: {
highlightColor: "lightblue",
},
};
const onClickNode = function (nodeId) {
window.alert(`Clicked node ${nodeId}`);
};
const onClickLink = function (source, target) {
window.alert(`Clicked link between ${source} and ${target}`);
};
const onMouseOverNode = function (nodeId, node) {
window.alert(`Alarms for ${nodeId} Coords: (${node.x}, ${node.y})`);
};
const onRightClickNode = function (event, nodeId) {
const clickedNode = { nodeId };
window.alert(`onRightClickNode link ${event} and ${nodeId}`);
};
return (
<div>
<Graph
id="graph-id"
data={this.state.data}
config={myConfig}
onClickNode={onClickNode}
onClickLink={onClickLink}
onRightClickNode={onRightClickNode}
/>;
</div>
);
}
}
export default GraphView
Because you are directly manipulating the state rather than using
setState
. In react you must never manipulate the state directly. So changeto: