user6002037
user6002037

Reputation:

React render Chart.js based on api response

I am using reacts and chart.js, and the chart-js/react wrapper. I am dynamically pulling the data from an API and then basing the chart on the data returned. The issue is that it is only one name from the API call that is being displayed in the graph. There should be three names.

I think the problem is that the rendering of the Graph component is being rendered before all the data has been returned by the API, so the graph only contains the first name. At least this is what i think. I have tried working with the componentWillMount function but cannot get it working.

can anyone spot anything wrong with my code below?

var App = React.createClass({

    getInitialState: function(){
        return {
            names: []
        }
    },

    componentDidMount: function() {
        $.get(url, function (data) {
            this.setState({ names: data })
        }.bind(this));
    },

    render: function() {
        return(
            <div>
                <Graph names={this.state.names}/>               
            </div>
        )
    }
});

var Graph = React.createClass({

    render: function() {
        for(var i = 0; i < this.props.names.length; i++) {
            names.push(this.props.names[i].name)
        }
        var chartData =  {
            labels: names,
            datasets: [{
                   data: goals
                },
                {
                    data: predictions
                }]
        };
        return <LineChart data={chartData} width="600" height="250"/>
    }
});

Upvotes: 1

Views: 4120

Answers (1)

The Reason
The Reason

Reputation: 7973

You have to control your state like below:

var App = React.createClass({
    getInitialState: function(){
        return {
            names: [],
            isLoaded: false
        }
    },
    componentDidMount: function() {
        $.get(url, function (data) {
            this.setState({ 
                names: data,
                isLoaded: true
            })
        }.bind(this));
    },
    render: function() {
        return(
            <div>
                {this.state.isLoaded ? <Graph names={this.state.names}/> : <div>Still Loading... </div> }
            </div>
        )
    }
});

So once you get all your data you can render your chart otherwise show the loading screen. Take a look at this Link probably it will be helpfull for you. Hope it makes sense for you.

Upvotes: 5

Related Questions