I have an issue with my admin dashboard partly I have not done a thing like this before but essentially I am trying to get ready data that ant design graphs will use. This data is coming from mongodb through redux useSelector. Then I map the data and store it in useState of array type
const [data, setdata] = React.useState([]);
const [reference, setreference] = React.useState([]);
const [orderActivity, setorderActivity] = React.useState([]);
const {
dataStreamMonthly = [],
user,
orders = [],
} = useSelector((state) => state.auth) ?? {};
React.useEffect(() => {
dispatch(getMonthlyRevenue(user.refreshToken));
dispatch(getOrders(user.refreshToken));
}, [dispatch]);
React.useEffect(() => {
let monthList = [
"N/A",
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
const source =
dataStreamMonthly &&
dataStreamMonthly.map((stage) => {
const monthName = stage._id.month
? monthList[parseInt(stage._id.month)]
: "N/A";
return { type: monthName, revenue: stage.amount };
});
setdata(source);
}, [dataStreamMonthly, orders]);
Now the issue is when the component initially renders data is null but that should not be the case since data is an array. So this is where I use it for the graph.
const config1 = {
data,
xField: "type",
yField: "revenue",
color: ({ type }) => {
return "#ffd333";
},
label: {
// 可手动配置 label 数据标签位置
position: "middle",
// 'top', 'bottom', 'middle',
// 配置样式
style: {
fill: "#FFFFFF",
opacity: 0.6,
},
},
xAxis: {
label: {
autoHide: true,
autoRotate: false,
},
},
meta: {
type: {
alias: "Month",
},
sales: {
alias: "Revenue",
},
},
};
And subsequently render it
<div>
<Column {...config1} />
</div>
I keep getting data is not defined so I conditionally render based on data
<div>
data.length && <Column {...config1} />
</div>
Still get the error data is not defined. Please help for I am out of options
2
Answers
The problem lies within the piece of code where you are trying to set the data here
when
dataStreamMonthly
resolves to false it returnundefined
you should default it to an empty array by using|| []
or using a tenary expression instead of the&&
, this is what I would go forI think when you try to run your frist useEffect, where you dispatch both action. You did not get user.refreshToken value. So please try to console your user.refreshToken value in first useEffect.