'ReactJs page renders fine when using .map of objects but if use index of array runs on first save but crashes on reload
I am creating a flashcard app, already have a page where I use .map() to render all items. Now I created another page so I can individually show one card at a time, so instead of using .map I used items[x] so I can increment by one with a onClick button. When I first save the file the live update renders fine as predicted, yet if I reload the page it crashes saying that it cannot read the word property of undefined. Now after doing some debugging I found that If I console log the array at first it shows up as zero/0 then prints out again with the info, even though I call the useSelector function to gather the info from the state before trying to access the data. Now this happens no matter if I use the .map() function but for some reason the .map() function does not crash and render fine as expected.
import React from "react";
import FlippableFlashcard from "../FlippableFlashcards/FlippableCard/FlippableCard.jsx";
import { Button, Container, Box } from "@mui/material";
import ArrowRightIcon from "@mui/icons-material/ArrowRight";
import ArrowLeftIcon from "@mui/icons-material/ArrowLeft";
import { useSelector } from "react-redux";
import useStyles from "./styles.js";
const Practice = () => {
const classes = useStyles();
const items = useSelector((state) => state.posts);
const handleAdd = () => {};
return (
<>
<Container className={classes.centerDiv}>
<FlippableFlashcard item={console.log(items[0])} />
{/*//This fails, but this does not <FlippableFlashcard item={items.map((item) => console.log(item))} />*/}
</Container>
<Box textAlign="center" className={classes.ButtonBar}>
<Button onClick={handleAdd}>
<ArrowLeftIcon />
</Button>
<Button>
<ArrowRightIcon />
</Button>
</Box>
</>
);
};
export default Practice;
specifically this <FlippableFlashcard item={console.log(items[0])} />
Error:
FlippableCard.jsx:20 Uncaught TypeError: Cannot read properties of undefined (reading 'word')
So I know it is because of that first console log being 0/null/undefined. Tried doing { items && items[0] } as I saw some saying this would work but did not.
Solution 1:[1]
Thanks to Akshay Mathur, I just simply did, works great, basically checks if data exists if not then simply console logs fetching, on the second auto reload it will render.
{items.length ? (
<FlippableFlashcard item={items[x]} key={items[x]._id} />
) : (
console.log("fetching data")
)}
Solution 2:[2]
Do something like this:
{items.length > 0 && items.map((item,index)=>(<FlippableFlashcard item={item} key={index} />)}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | tester0001 |
| Solution 2 | Hafid Denguir |
