Chartjs-Display Json from Node.js in Chart.js with React

0👍

You need to use fetch to make an api call to the backend.

getchartData = () => {
    // Make request to the node backend. You might need to enable CORS in the express app.
    fetch("http://localhost:3000/") 
    .then(res => res.json())
    .then((jsonarray) => {
        var labels = jsonarray.map(function(e) {
            return e.Name;
        });
        var data = jsonarray.map(function(e) {
            return e.Value;
        });

        this.setState({
            chartData:{
                labels:labels,
                datasets:[
                    {
                        label:'Popuplation',

                        data:data
                    }
                ]
            }
        });
    });
}

Also you can remove the state in Chart.js as it is unnecessary and use props directly.

render() {
        return(
            <div className="Chart">

                <Line
                    data={this.props.chartData}


                ...

Working Stackblitz example

Leave a comment