I have an API that responds with the following object:-
[
{
"A":4,
"B":3,
"C":2,
"D":1,
}
]
I want to display the object data in the following component:-
export default function name() {
const dispatch = useDispatch();
const { postsInfo } = useSelector((state) => state.posts);
useEffect(() => {
dispatch(getPostsInfo());
}, [dispatch]);
console.log(postsInfo[0]);
return (
<>
<div className="db-wrapper">
<div className="cards-container">
<Card title={"A"} value={postsInfo[0].A} />
<Card title={"B"} value={postsInfo[0].B} />
<Card title={"C"} value={postsInfo[0].C} />
<Card title={"D"} value={postsInfo[0].D} />
</div>
</div>
</>
);
}
but whenever the page is rendered it throws an error in the console log and nothing is shown on the page.
Uncaught TypeError: Cannot read properties of undefined (reading '0')
postsasundefined. You'll either need to check forundefinedand render something different, or change the initial state sopostsis an object with a[0]property