0๐
You are making the request for your data in the componentWillMount
hook, but it is possible that you are getting the response after the component has been mounted (i.e. after the componentDidMount
has been executed).
The use of componentWillMount
to make requests is discouraged (note that the method is considered legacy and you should avoid using it):
Avoid introducing any side-effects or subscriptions in this method. For those use cases, use componentDidMount() instead.
Also, your render method is assigning a value to this.state.render
instead of checking if it is true or not to render the canvas
element.
Lastly, the data stored in the state
of your component should be data that affects the DOM you want to render (since calling setState
causes the render
method to execute). But in your code, you are rendering your chart through a canvas
. Therefore, the data for your chart is not affecting the DOM you are rendering.
Taking all the previous points into account, you can render an empty canvas
element from the start (i.e. no need for state.render
), make the request in the componentDidMount
hook and once you have the info, render the chart:
class BarChart extends Component {
constructor(props){
super(props);
this.state = {};
}
componentDidMount() {
this.getGraphs().then(info => {
const data = {
labels: info.categories,
datasets: [{
label: "Number of Tweets by Sentiment Category",
backgroundColor: "blue",
data: info.count
}]
};
this.renderChart(data);
})
}
renderChart(data) {
let el = ReactDOM.findDOMNode(this.refs.chart);
let ctx = el.getContext("2d");
let chart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
barValueSpacing: 20,
scales: {
yAxes: [{
ticks: {
min: 0
}
}]
}
}
});
}
getGraphs() {
let ticker = this.state.crypto;
let name = this.state.name;
let URL = 'http://localhost:5000/api/getGraphs';
return fetch(URL, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'name': name,
'ticker': ticker,
}
})
.then((response) => response.json())
}
render() {
return (
<div className='card'>
<canvas ref="chart" height="400px" />
</div>
);
}
}
export default BarChart;
Also, I noticed that in the getGraphs
method you are reading the crypto
and name
attributes from the state
, but in your question you are not declaring them.
0๐
This line seems to be incorrect. You are assigning a value here and not checking if its true.
{ this.state.render = true &&
<canvas ref="chart" height="400px" />
}
Change it to :
{ this.state.render &&
<canvas ref="chart" height="400px" />
}
It may not be the root cause, but just want to point it out.