I am getting an error in BarChart
:
undefined is not iterable!
The response I am getting from API is:
{
"saleCharts": [
{
"priceSum": 0,
"categoryName": "string"
}
],
"statusCharts": [
{
"qtySum": 0,
"status": "string"
}
]
}
The code I have written in React
is:
function Dashboard({ notifyData }) {
const [orderData, setOrderData] = useState([]);
const [dashboardData, setDashboardData] = useState([]);
const [newOrderCount, setNewOrderCount] = useState(0);
useEffect(() => {
getNewOrder();
}, [notifyData]);
var getNewOrder = function () {
let orderResp = [];
axios.get(GetNewOrdersUrl + '/2').then(response => {
orderResp = response.data;
})
.then(() =>
axios.get(OrderDashboardUrl).then(response => {
setOrderData(orderResp.orderList);
setNewOrderCount(orderResp.count);
setDashboardData(response.data.saleCharts);
}))
};
}
return (
<>
<BarChart
xAxis={[
{
id: 'barCategories',
data: dashboardData.map(item => item.categoryName),
scaleType: 'band',
},
]}
series={[
{
data: dashboardData.map(item => item.priceSum),
},
]}
colors={['#d75b47']}
width={1000}
height={350}
/>
</>
)
Please suggest why I getting that problem and provide the solution.
What I understand is the BarChart
component is rendering first before the state.
The issue is related to the series
prop of the BarChart
component. It requires the series
prop describing the data to render. The series
prop gets an array and should include the data objects. None of the data objects shouldn't have any undefined values. See: BarChart Documentation
Therefore, there can be applied two solutions to prevent this issue.
dashboardData
state:const [dashboardData, setDashboardData] = useState([ { priceSum: 0 } ]);
BarChart
component only when the dashboardData
state has values. Therefore, it will not be rendered in the first render since dashboardData
has no length:return (
!!dashboardData.length && (
<BarChart ... />
)
);
Here is DEMO LINK to test and review it easily.
Hope, it's helpful and clear for anyone who needs it.