Here is my React component:
const ChartItem = ({ id, apiUrl }) => {
const [nivoChartData, setNivoChartData] = useState([]);
//
//declare the API call
const apiCallAndConversionForNivoFormat = useCallback(async () => {
try {
const response = await axios.get(apiUrl);
console.log("response: ");
console.log(response);
//converting api response into the format needed by nivo charts
const dataConvertedForNivo = [
{
id: response.data.symbol,
color: "hsl(90, 70%, 50%)",
data: response.data.historical.forEach((key) => {
key["x"] = key["date"];
key["y"] = key["close"];
delete key["date"];
delete key["close"];
}),
},
];
console.log("dataConvertedForNivo: ");
console.log(dataConvertedForNivo);
setNivoChartData(dataConvertedForNivo);
} catch (e) {
console.error(e);
}
}, [setNivoChartData, apiUrl]);
useEffect(() => {
apiCallAndConversionForNivoFormat();
}, [apiCallAndConversionForNivoFormat]);
return (
<div className="chart-item">
<NivoLineChart key={id} nivoData={nivoChartData} />
</div>
);
};
The original API response format before modifying:
{
"symbol": "AAPL",
"historical": [
{
"date": "2021-02-24",
"close": 125.349998
},
{
"date": "2021-02-23",
"close": 125.860001
},
{
"date": "2021-02-22",
"close": 126
},
]
}
^ I believe the response log is now showing "x" and "y" instead of "date" and "close" due to memoization.
nivo chart example format that I need to convert to:
[
{
"id": "AAPL",
"color": "hsl(90, 70%, 50%)",
"data": [
{
"x": "2021-02-24",
"y": 125.349998
},
{
"x": "2021-02-23",
"y": 125.860001
},
{
"x": "2021-02-22",
"y": 126
},
]
}
]
Can anyone understand why the dataConvertedForNivo.data is undefined? And is there any better way to do this response conversion?
You need to replace forEach
with map
.
const dataConvertedForNivo = [
{
id: response.data.symbol,
color: "hsl(90, 70%, 50%)",
data: response.data.historical.map(key => {
key["x"] = key["date"];
key["y"] = key["close"];
delete key["date"];
delete key["close"];
return key;
}),
},
];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.