So there are three components namely: Devdropdown , the main one and two child ones are Tables.jsx and Chart.jsx.
So, the table got displayed while passing props from the parent component. And I wanted the same way for the Pie Chart to occur as well. The scene is, the user selects an option from the dropdown which enables them to see the table data along with the Pie Chart. I am having issues with the Pie Chart. At times it is being displayed, at times it isn’t. Here are the three jsx files:
Devdropdown.jsx:
import React, { useState, useEffect, useMemo } from "react";
import Tables from "./Tables";
import Chart from "./Chart";
const Devdropdown = () => {
const [devices, setDevices] = useState([{}]);
const [selected, setSelected] = useState();
const url = "..";
useEffect(() => {
async function getDevices() {
const response = await fetch(url);
const body = await response.json();
setDevices(body.data);
}
getDevices();
}, []);
const handleChange = (e) => {
e.preventDefault();
setSelected(e.target.value);
};
const deviceMap = useMemo(() => {
const grouped = new Map();
for (const device of devices) {
const currDeviceArr = grouped.get(device.device_id) ?? [];
currDeviceArr.push(device); // adding the current device to the associated device_id array
grouped.set(device.device_id, currDeviceArr);
}
return grouped;
}, [devices]);
console.log(deviceMap);
return (
<React.Fragment>
<div className="container">
<div className="input">
<h1>Aircraft {selected}</h1>
<select
value={selected}
onChange={handleChange}
placeholder="select an option"
>
{devices
? Array.from(deviceMap.keys(), (device_id) => (
<option key={device_id} value={device_id}>
{device_id}
</option>
))
: null}
</select>
<br />
<br />
<Tables data={deviceMap.get(selected)} />
</div>
<div>
<Chart chartData={deviceMap.get(selected)} />
</div>
</div>
</React.Fragment>
);
};
export default Devdropdown;
Tables.jsx:
import React from "react";
import Table from "react-bootstrap/Table";
const Tables = ({ data = [] }) => {
return (
<Table striped bordered>
<thead>
<tr>
<th>Timestamp</th>
<th>Location</th>
</tr>
</thead>
<tbody>
{data.map((device, i) => (
<tr key={i}>
<td>{device.timestamp}</td>
<td>{device.location}</td>
</tr>
))}
</tbody>
</Table>
);
};
export default Tables;
Chart.jsx:
import React from "react";
import { PieChart, Pie } from "recharts";
const Chart = ({ charData = [] }) => {
return (
<PieChart width={700} height={700}>
<Pie
data={charData.map((device) => device.location)}
dataKey="locations"
outerRadius={250}
fill="green"
/>
</PieChart>
);
};
export default Chart;
Here is how deviceMap looks like in the console. As you can see, I have already clicked on an option and the table details are also present. The same way , a Pie Chart should also be there with the Locations . If you guys could spare your time and tell me what should be done.