1

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?

1 Answer 1

1

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
  }]
};
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.