'How can I express variables with array in JSX?
I am a beginner learning ReactJs. I am trying to express data from firebase.
when I put {quizes[0].quiz} this was working. But, if I want to use 'qno' variable, what should I do?
import {useParams} from "react-router-dom";
import {dbService} from 'fbase';
const QuizPlay = () => {
const {cateId} = useParams();
const [qno, setQno] = useState(0);
const [quizes, setQuizes] = useState([]);
useEffect(() => {
dbService
.collection("quizes")
.where('cateId','==',cateId)
.orderBy("createdAt", "desc")
.onSnapshot((snapshot) => {
const quizArray = snapshot.docs.map((doc) => ({
id: doc.id,
...doc.data(),
}));
setQuizes(quizArray);
})
}, [cateId]);
return (
<div className="container">
{quizes[qno].quiz} <=== error
</div>
)
}
export default QuizPlay;
Solution 1:[1]
Before quizes has been populated quizes[qno] - (quizes[0]) - is undefined and therefore does not have a quiz property.
Try
<div className="container">
{quizes[qno]?.quiz}
</div>
assuming your compiler supports optional chaining, or if not:
<div className="container">
{quizes.length > 0 && quizes[qno].quiz}
</div>
Solution 2:[2]
I think it's happening because when the component is mounted the first time the quizzes haven't been loaded yet. So quizes is empty. Try this:
{quizes && quizes[qno].quiz}
Or
{quizes.length > 0 && quizes[qno].quiz}
Could you tell us exactly what error your getting?
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 | Daniel Storey |
| Solution 2 | Obsidianlab |
