-2
I am developing a quiz application using React for study purposes.
I have the state called Quiz, the same consists of:
interface QuestionData {
id: number;
question: string;
explanation: string;
options: OptionsData;
}
I would like to display only the first element of the array on the screen, I know the way to do this would be:
<p>{quiz[0].question}</p>
But this way I’m getting the following error:
TypeError: Cannot read property 'question' of undefined
If I print using console.log(quiz[0].question)
, I receive the desired return.
Is there any other way? Or the way I thought it was right is not?
Complete code below:
interface VideoInfo {
video_id: number;
}
type OptionsData = any[];
interface QuestionData {
id: number;
question: string;
explanation: string;
options: OptionsData;
}
const Quiz: React.FC<VideoInfo> = video_id => {
const [quiz, setQuiz] = useState<QuestionData[]>([]);
const video = video_id;
const getQuiz = useCallback(async () => {
try {
await api.get(`/quiz/video/${video}`).then(response => {
setQuiz(response.data);
});
} catch (err) {
alert('error');
}
}, [video]);
useEffect(() => {
getQuiz();
}, [getQuiz]);
return (
<Container>
<ol>
<li>
<div className="question">
{/* O erro acontece aqui: */}
<p>{quiz[0].question}</p>
<div>
<Button type="button">A</Button>
<Button type="button">B</Button>
<Button type="button">C</Button>
<Button type="button">D</Button>
</div>
</div>
</li>
</ol>
</Container>
);
};
export default Quiz;
This is the way out of console.log(response.data)
when invoked within the function getQuiz
:
Array(2)
0:
explanation: "Sempre é necessário redobrar a atenção ao sair da via para um
acostamente."
id: 6
options: (4) [{…}, {…}, {…}, {…}]
question: "Quais cuidados ao sair da via para um acostamento?"
1:
explanation: "Precisamos manter uma distância segura a todo momento."
id: 7
options: (4) [{…}, {…}, {…}, {…}]
question: "Para que tenhamos a menor distância de frenagem:"
What is
response.data
?– Luiz Felipe
Response is the return of the Promise that fetches the data of an API, data is an element that is within Response, which brings data array of the questions.
– Fred
quiz[0]
isundefined
at the beginning. Its initial value is[]
. Try the{quiz[0]?. question}
– Ajeet Shah
Sorry @Luizfelipe. I edited the question.
– Fred
Really @Ajeetshah, the problem was this, thank you very much!
– Fred