amcharts / amcharts3-react

Official amCharts V3 React component
Apache License 2.0
118 stars 50 forks source link

charts are blank while combaining amcharts v3 and reactjs #74

Open SaraNaifar opened 6 years ago

SaraNaifar commented 6 years ago

I am trying to make an API request (GET) then the received data should be appended on the graph as a statistatics , this is my code when i run it i got nothing on the graph.

import React, {Component} from 'react';
import AmCharts from "@amcharts/amcharts3-react";
import {Bar, Doughnut, Line, Pie, Polar, Radar} from 'react-chartjs-2';
import {CardColumns, Card, CardHeader, CardBody,Row, Col, Button, Modal, ModalHeader, ModalBody, ModalFooter} from 'reactstrap';
import axios from 'axios';
import Modals from '../Notifications/Modals/Modals.js';
import RangedDatePicker from '../DatePicker/RangedDatePicker.js';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import ButtonDropdowns from '../Buttons/ButtonDropdowns/ButtonDropdowns.js';

let loginPath = 'http://127.0.0.1:8000/api/reactions/daily';

let config = { 
  headers: {   
    'Access-Control-Allow-Origin': '*',
    'Authorization': 'Bearer '+localStorage.getItem('token') 
  },
  mode: 'no-cors'
};

class Charts extends Component {

 constructor(props) {

    super(props);

    const minDate = new Date();
    const maxDate = new Date();
    minDate.setFullYear(minDate.getFullYear() - 1);
    minDate.setHours(0, 0, 0, 0);
    maxDate.setFullYear(maxDate.getFullYear() + 1);
    maxDate.setHours(0, 0, 0, 0);

    this.state = {
    dataProvider: [],
    timer: null,
    minDate: minDate,
    maxDate: maxDate,
    autoOk: false,
  };

    this.handleChangeMinDate = this.handleChangeMinDate.bind(this);
    this.handleChangeMaxDate= this.handleChangeMaxDate.bind(this)
    this.getTimeRangeFromCalendar = this.getTimeRangeFromCalendar.bind(this);
    this.generateData=this.generateData.bind(this)
}

 generateData() {
   var successDataCount=[];
    axios.get('http://127.0.0.1:8000/api/reactions/daily?from=2017-01-01 &to=2018-06-04 ', config)
        .then((response )=> {

              for(let i=0 ; i<response.data[0].reactions.length;i++)
              { 
                var year =response.data[0].reactions[i].year;
                var month =response.data[0].reactions[i].month;
                var day =response.data[0].reactions[i].day;
                var dateOfReaction = new Date(year,month,day);
                var count = response.data[0].reactions[i].count;

                successDataCount.push({date:dateOfReaction ,count:count });
              }

               if (successDataCount){

                this.setState({dataProvider: successDataCount},function(){console.log('++++')});

                  for (var i = 0; i < 100; ++i) {
                    var firstDate = new Date();
                    var date = new Date(firstDate.getTime());
                    date.setDate(i);
                     //console.log(this.state.dataProvider)
                    this.state.dataProvider.push({
                      date: this.state.dataProvider.date,
                      value: this.state.dataProvider.count
                    });
                    }

                  }

  })

  .catch((error) => console.log(error))
}

componentDidMount() {
      // Update the chart dataProvider every 3 seconds

        this.setState({
          dataProvider: this.generateData()
        });
          this.generateData();
}

componentWillUnmount() {
  clearInterval(this.state.timer);
}

//Getting StartDate and EndDate from calendar to update charts
getTimeRangeFromCalendar(range){

  let from = JSON.stringify(range.startDate._d);
  let to = JSON.stringify(range.endDate._d);

  console.log('*************************CHOISEN STATISTICS*************************')
  let config = { 
    headers: {   
      'Access-Control-Allow-Origin': '*',
      'Authorization': 'Bearer '+localStorage.getItem('token') 
    },
    mode: 'no-cors',
    params :{
      from: from,
      to: to
    }

  };

  console.log(config.params)  
  console.log(config.params.to) 

  axios.get('http://127.0.0.1:8000/api/reactions/daily', { 
    headers: {   
      'Access-Control-Allow-Origin': '*',
      'Authorization': 'Bearer '+localStorage.getItem('token') 
    },
    mode: 'no-cors',
    params :{
      from: from,
      to: to
    }

  } )
  .then((response )=> console.log(response.data))
  .catch((error) => console.log(error))

}
  handleChangeMinDate(event, date) {
    this.setState({
      minDate: date,
    } , function(){console.log(this.state.minDate)});
  };

  handleChangeMaxDate(event, date) {
    this.setState({
      maxDate: date,
    });
  };

render() {
 const config = {
...
  }],
  "balloon": {
    "borderThickness": 1,
    "shadowAlpha": 0
  },
  "graphs": [{
  ...
  }],
  "chartScrollbar": {
 ...
  },
  "chartCursor": {
  ...
  },
  "valueScrollbar":{
  ...
  },
  "dataProvider": this.state.dataProvider
};
return (

  <div className="animated fadeIn">
  <CardColumns className="cols-2 column-count-1">
  <Row>
  <Col>
  <Card>
  <CardHeader>
  <i className="fa fa-align-justify"></i> Choosing parameters
  </CardHeader>
  <CardBody>

  <MuiThemeProvider>
  <RangedDatePicker  sendMinDate={this.handleChangeMinDate} sendMaxDate= {this.handleChangeMaxDate}/>
  </MuiThemeProvider>
  <ButtonDropdowns/>

  </CardBody>
  </Card>
  </Col>
  </Row>

  <Card>
  <CardHeader>
  Statistics
  <div className="card-actions">
  <a href="http://www.chartjs.org">
  <small className="text-muted">docs</small>
  </a>
  </div>
  </CardHeader>
  <CardBody>

  <div className="App">

  <AmCharts.React style={{ width: "100%", height: "500px" }} options={config} />
  </div>
  </CardBody>
  </Card>

  </CardColumns>
  </div>

  )
}
}

export default Charts;
Pauan commented 6 years ago

@SaraNaifar I apologize for the delay.

Why are you using setState to update the dataProvider and then afterwards pushing into the dataProvider? You should make all your changes first and then call setState.

Similarly, you're calling this.setState({ dataProvider: this.generateData() }); and then afterwards calling this.generateData(); again. You only need to call it once.

Also, I do not understand what this code is doing:

for (var i = 0; i < 100; ++i) {
  var firstDate = new Date();
  var date = new Date(firstDate.getTime());
  date.setDate(i);
  //console.log(this.state.dataProvider)
  this.state.dataProvider.push({
    date: this.state.dataProvider.date,
    value: this.state.dataProvider.count
  });
}

this.state.dataProvider is an array, so it doesn't have a date or count property.