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;
CodePudding user response:
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>
CodePudding user response:
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?