Is there any method to map or represent API data to Chart in ReactJS?

0

Issue

I am using API data for showing it in a graphical representation using React Charts.
The API data looks like:

0:
CPSA: "0.00"
CRSA: "0.00"
XBA: "0.00"
XSA: "0.00"
audbal: "1.00"
audnet: "1.00"
date: "2021-12-25T05:31:40.497Z"
xnaaud: "0.0100000000"
xnabal: "100.0000000000"
__v: 0
_id: "617d00f1e85e769931f42483"
[[Prototype]]: Object
1:
CPSA: "11.81"
CRSA: "40.95"
XBA: "20.00"
XSA: "0.00"
audbal: "73.76"
audnet: "72.76"
date: "2021-12-25T06:11:14.824Z"
xnaaud: "0.0119063760"
xnabal: "6195.0000000000"
__v: 0
_id: "61c6b6025547fdf4cd6ecb6c"

I want to map the xnaaud and date attributes onto the Chart.
I am using code:

const [Data, setData] = useState([]);
    const data = {
            labels: [Data.date],
            datasets: [
              {
                label: 'XNA/AUD',
                fill: false,
                lineTension: 0.0,
                backgroundColor: 'rgb(41, 33, 116,0.5)',
                borderColor: 'rgb(41, 33, 116,0.5)',
                pointHitRadius: 20,
                data:[parseFloat(Data.xnaaud)],
              },
            ]
          };
     useEffect(() => {
            async function fetchBooks() {
              const response = await fetch('/audlogget');
              const json = await response.json();
              setData(json.al);
              console.log(json.al)
          }
          fetchBooks();
      },[]);
    if(!Data)
    {
      return <Loading/>;
    }
      return (
        <div className="chart">
          <Line data={data} />
        </div>
      )
    }

But the issue is that the values are not representing in the graph. The graph shows nothing when uses API data but when giving static values to labels and data it is working.
Whats the issue in the code?

Solution

Data seems to be an array of objects, the structure you mention to be the API data. In that case, this data must be mapped to individual arrays in order to obtain data.labels and the data of the unique dataset.

This could be done as follows:

const data = {
  labels: Data.map(o => o.date), // first change
  datasets: [{
    label: 'XNA/AUD',
    fill: false,
    lineTension: 0.0,
    backgroundColor: 'rgb(41, 33, 116,0.5)',
    borderColor: 'rgb(41, 33, 116,0.5)',
    pointHitRadius: 20,
    data: Data.map(o => parseFloat(o.xnaaud)) // second change
  }]
};

Answered By – uminder

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More