[Chartjs]-How to make aspecific API call from within a Line Chart class in ReactJS using react-chartjs-2?

1👍

Add a container Component & use Props

The component you’ve shown us here looks like a presentational component (has html structure, cares about how things look). What you should do is create a container component, these components care about things like logic & getting data. You can read about this design methodology here.

The container will render the component you have posted above but will pass some props kind of like this.

Example

class PlanGraphContainer extends Component {
  state = {
    dataToPass: []
  };

  async componentDidMount() {
    const response = await fetch('https://your-api-request');
    const data = await response.json(); // maybe you need this, you have to check your response
    this.setState({dataToPass: data});
  }

  render() {
    return <PlanGraph data={this.state.dataToPass} />
  }
}

Then inside your PlanGraph use this.props.data to see the data that is being passed. make sure you have some fake data or loading state whilst you wait for the request to be complete. our you can add something like this

render() {
  const { dataToPass } = this.state;
  return (dataToPass && dataToPass.length)
    ? <PlanGraph data={this.state.dataToPass} />
    : null;
}

Leave a comment