1

I am able to render each chart separately but I have no idea how to render multiple charts at the same time. Here is my code:

import React, { Component } from "react";
import {Line} from 'react-chartjs-2';

import axios from 'axios';

class Chart extends Component {
    constructor(props) {
        super(props);
        this.state = {
           chartData: {},
           data: []
      }
    }

    componentDidMount() {
        axios.get('https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=2&page=1&sparkline=true')

        .then(res => {

            const x = res.data;
            let y = [];
            x.forEach(element => {
                y.push(element.sparkline_in_7d.price)
            })

             console.log(y);

            this.setState({ 

                    chartData: {
                        labels: y,
                        datasets:[{
                            data: y,
                        }
                     ]
                    },
                    data: y

            })
        })
    }


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


         //*WORKS*
              {/* {this.state.data.map((n, index) => {
                               return (
                                <li key={index}>{n}</li>
                            );
                })} */}


       //*DOES NOT WORK*
               {this.state.chartData.map((n, index) => {
                               return (

                                <Line key={index} data={n}/>
                            );
                })} 



            </div>
        );
    }
}

export default (Chart);

Normally I don't have any issues mapping data but I am having issues doing so with chartjs as when I try this it says it is not a function. Any help here would be appreciated.

1
  • Check the updated answer. Commented Jul 9, 2019 at 9:51

1 Answer 1

1

chartData should be an array.

Try the following approach.

//init state

this.state = {
   chartData: [],
}


//service inside componentDidMount

axios.get('https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=2&page=1&sparkline=true')
  .then(res => {
      const x = res.data;
      let chartData = [];
      x.forEach(element => {
        chartData.push({
          labels: element.sparkline_in_7d.price,
           datasets:[{data: element.sparkline_in_7d.price}]
         });
      });
     this.setState({chartData});
})

Here is the fiddle. https://codesandbox.io/s/sharp-wildflower-23hy7

Hope it will helps you.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.