I am developing a Quiz application using React / Typescript for the purpose of study.
I have the state called Quiz, it 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 that the way to do this would be:
<p>{quiz[0].question}</p>
But, in this way, I am getting the following error:
TypeError: Cannot read property 'question' of undefined
If I print using console.log (quiz[0].question), I get the desired return. Is there any other way? Or the form I thought was correct isn't it?
Full 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">
{/* The error happens here: */}
<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;