1

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;

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

3 Comments

Wow {quizes[qno]?.quiz} is working!!!!
Thank you so much. {quizes[qno]?.quiz} <---- how does it work? What ? mean? I appreciate it anyway.
0

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?

1 Comment

It says too many re-renders. I think I should not combine useState constant.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.