0

This is my json:

[
    {
        "day": 1,
        "commentNumber": 0
    },
    {
        "day": 2,
        "commentNumber": 0
    },
    {
        "day": 3,
        "commentNumber": 0
    },
    {
        "day": 4,
        "commentNumber": 0
    },
    {
        "day": 5,
        "commentNumber": 0
    },
    {
        "day": 6,
        "commentNumber": 0
    },
    {
        "day": 7,
        "commentNumber": 0
    },
    {
        "day": 8,
        "commentNumber": 0
    }
]

And here is my code:

export default class CommentsPerDayGraph extends Component {
  constructor(props) {
    super(props);
    this.state = {
      chartData: {},
    };
  }

  componentDidMount() {
    this.getStatistics();
  }

  getStatistics = () => {
    let labels = [];
    let data = [];

    CommentApi.getCommentsPerDay().then((response) => {
      let jsonProducts = JSON.parse(response.data);
      Object.keys(jsonProducts).map((key) => {
        labels.push(key);
        data.push(response.data[key]);
      });

      this.setState({
        chartData: {
          labels: labels,
          datasets: [
            {
              labels: '',
              data: data,
              backgroundColor: 'rgba(255,99,132,0.2)',
              borderColor: 'rgba(255,99,132,1)',
              borderWidth: 1,
              hoverBackgroundColor: 'rgba(255,99,132,0.4)',
              hoverBorderColor: 'rgba(255,99,132,1)',
            },
          ],
        },
      });
      console.log(this.state.chartData);
    });
  };

  render() {
    return (
      <div>
        <Bar data={this.state.chartData} />
      </div>
    );
  }
}

Zachary Haber
  • 10,376
  • 1
  • 17
  • 31
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Yury Tarabanko May 25 '20 at 13:36
  • That's actually not the issue here, the setState call is in the `.then`. – Zachary Haber May 25 '20 at 13:42
  • Not really, for me the problem is that I can't build the chart based on the data I receive on apiCall – Tanta Adina May 25 '20 at 13:43

1 Answers1

0

It looks like the only thing you have to do is change data.push(response.data[key]); to data.push(jsonProducts[key]);

response.data is a string rather than the array you want to index. jsonProducts is the array you get once you parse the response.data, so you should be using that instead.

Assuming everything else of your logic is accurate because I don't have anything to base the results on, this should be the only thing you need to change.

const CommentApi = {
  getCommentsPerDay() {
    return new Promise((res) =>
      res({
        data: `[
          {
              "day": 1,
              "commentNumber": 0
          },
          {
              "day": 2,
              "commentNumber": 0
          },
          {
              "day": 3,
              "commentNumber": 0
          },
          {
              "day": 4,
              "commentNumber": 0
          },
          {
              "day": 5,
              "commentNumber": 0
          },
          {
              "day": 6,
              "commentNumber": 0
          },
          {
              "day": 7,
              "commentNumber": 0
          },
          {
              "day": 8,
              "commentNumber": 0
          }
      ]`,
      })
    );
  },
};

class CommentsPerDayGraph extends React.Component {
  state = { chartData: {} };

  componentDidMount() {
    this.getStatistics();
  }

  getStatistics = () => {
    let labels = [];
    let data = [];

    CommentApi.getCommentsPerDay().then((response) => {
      let jsonProducts = JSON.parse(response.data);
      Object.keys(jsonProducts).map((key) => {
        labels.push(key);
        data.push(jsonProducts[key]);
      });

      this.setState({
        chartData: {
          labels: labels,
          datasets: [
            {
              labels: '',
              data: data,
              backgroundColor: 'rgba(255,99,132,0.2)',
              borderColor: 'rgba(255,99,132,1)',
              borderWidth: 1,
              hoverBackgroundColor: 'rgba(255,99,132,0.4)',
              hoverBorderColor: 'rgba(255,99,132,1)',
            },
          ],
        },
      });
      console.log(this.state.chartData);
    });
  };

  render() {
    return (
      <div>
        {/*<Bar data={this.state.chartData} />*/}
        {JSON.stringify(this.state.chartData)}
      </div>
    );
  }
}

ReactDOM.render(<CommentsPerDayGraph />, document.querySelector('#root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"/>
Zachary Haber
  • 10,376
  • 1
  • 17
  • 31
  • What is the error? And can you post more of what your CommentApi looks like? – Zachary Haber May 25 '20 at 14:09
  • This is the error: Unhandled Rejection (SyntaxError): Unexpected token o in JSON at position 1 – Tanta Adina May 25 '20 at 14:15
  • Sounds like the `JSON.parse` isn't seeing actual JSON. If you `console.log` the `response.data`, what does that give you exactly? – Zachary Haber May 25 '20 at 14:16
  • Array(30) 0: {day: 1, commentNumber: 0} 1: {day: 2, commentNumber: 0} 2: {day: 3, commentNumber: 0} 3: {day: 4, commentNumber: 0} 4: {day: 5, commentNumber: 0} 5: {day: 6, commentNumber: 0} 6: {day: 7, commentNumber: 0} 7: {day: 8, commentNumber: 0} 8: {day: 9, commentNumber: 0} 9: {day: 10, commentNumber: 0} 10: {day: 11, commentNumber: 0} 11: {day: 12, commentNumber: 0} 12: {day: 13, commentNumber: 0} – Tanta Adina May 25 '20 at 14:21
  • `const jsonProducts = response.data` and you should be good. Looks like the data is already an array rather than a string. – Zachary Haber May 25 '20 at 14:22
  • So far so good, but it still doesn't display the graph according to the data, on labels it's okay, but not on data – Tanta Adina May 25 '20 at 14:30
  • You might consider making that a new question and give more information like the data structure your graph is expecting. – Zachary Haber May 25 '20 at 14:32