Reputation: 1
I'm Working with react on an API that returns an array[2] and inside has another Array [11] that inside have 11 arrays with the data i need and some that I don't need to fetch. I'm using axios to make the get request and I'm able to print the data with console.log and i geI a 200, but I need to extract the values of time and mean and pass that data to a chart, can someone help me I'm a bit stuck
I try to use a map method but I it didn't work.
this is the code i try to use: ``` import React, { useEffect, useState } from 'react'; import axios from 'axios'; import { Line } from 'react-chartjs-2';
const URLAPI = 'apiurl'
try {
const response = await axios.get(URLAPI);
const data = response.data.data[2][0].map(item => item.mean);
setChartData(data);
} catch (error) {
console.log(error);
}
};
return (
<div>
<h1>Line Chart</h1>
<Line
data={{
labels: Array.from(Array(chartData.length).keys()), // Use index as
labels
datasets: [
{
data: chartData,
label: 'Mean Values',
borderColor: 'blue',
fill: false,
},
],
}}
/>
</div>
);
}
export default LineChartComponent;
Upvotes: 0
Views: 700
Reputation: 35
I added some modifications to your code. Use the Array.prototype.flat() method to flatten the nested array it will be easier to access the inner arrays. Then, you can use the map() method to extract the time and mean values from each inner array.
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { Line } from 'react-chartjs-2';
const LineChartComponent = () => {
const [chartData, setChartData] = useState([]);
useEffect(() => {
const fetchData = async () => {
try {
const response = await axios.get(URLAPI);
const nestedArray = response.data.data[2][0];
const flattenedArray = nestedArray.flat(); // Flatten the nested array
const data = flattenedArray.map(item => ({
time: item.time,
mean: item.mean
}));
setChartData(data);
} catch (error) {
console.log(error);
}
};
fetchData();
}, []); // Empty dependency array to run the effect only once
return (
<div>
<h1>Line Chart</h1>
<Line
data={{
labels: chartData.map(item => item.time), // Use time values as labels
datasets: [
{
data: chartData.map(item => item.mean), // Use mean values as data
label: 'Mean Values',
borderColor: 'blue',
fill: false,
},
],
}}
/>
</div>
);
};
export default LineChartComponent;
Upvotes: 0