Within my React Native Quiz function, I have implemented a fetch GET request to load data. Upon checking if the data has loaded using the showQuestion
variable, I encounter an error message:
Cannot read properties of undefined (evaluating 'questObj[currentQuestion].questionText')
I attempted to print the data using questObj[currentQuestion]
, which reveals an object filled with data. The image below showcases the result of the console.log
.
console.log(questObj[currentQuestion]);
https://i.sstatic.net/d0Y5A.png
Any insights on where I might be going wrong? (Given my novice status in React Native, it could very well be due to a fundamental mistake from my end.)
export function Quiz(this: any) {
const styles = StyleSheet.create({
container: {
backgroundColor: '#B86566',
width: '100%',
height: '100%',
alignItems: 'center',
justifyContent: 'center'
},
headingColumn: {
flexBasis: '90%',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
flex: 1,
padding: 20,
fontSize: 30,
},
buttonColumn: {
flexBasis: '35%',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
flex: 1,
padding: 20,
margin: 20,
borderColor: 'white',
borderWidth: 1
},
row: {
display: 'flex',
flexDirection: 'row',
flexWrap: 'wrap',
width: '100%'
},
});
const [showScore, setShowScore] = useState(false);
const [showQuestion, setShowQuestion] = useState(false);
const [currentQuestion, setCurrentQuestion] = useState(0);
const [score, setScore] = useState(0);
const [questionArray, setQuestions] = useState(0);
useEffect(() => {
getQuestions();
}, []);
let questObj: {
questionText: any;
answerOptions: any;
}[] = [];
const getQuestions = async () => {
try {
let response = await fetch(
'https://opentdb.com/api.php?amount=10&category=26&difficulty=medium&type=multiple'
);
let json = await response.json();
json.results.forEach((element: { question: any; correct_answer: any; incorrect_answers: any; }) => {
questObj.push({
questionText: element.question,
answerOptions: [{ answerText: element.correct_answer, isCorrect: true },
{ answerText: element.incorrect_answers[0], isCorrect: false },
{ answerText: element.incorrect_answers[1], isCorrect: false },
{ answerText: element.incorrect_answers[2], isCorrect: false }
],
},
);
console.log(questObj[currentQuestion]);
setShowQuestion(true);
});
} catch (error) {
console.error(error);
}
}
const handleAnswerButtonClick = (isCorrect: boolean) => {
if (isCorrect) {
setScore(score + 1);
}
const nextQuestion = currentQuestion + 1;
if (nextQuestion < questObj.length) {
setCurrentQuestion(nextQuestion);
} else {
setShowScore(true);
}
};
return <View style={styles.container}>
<View><Text></Text></View>
<View>{showScore ?
<Text>You scored {score} out of {questObj.length}</Text>
: <></>}
</View>
{showQuestion ?
<View>
<View >
<Text>Question {currentQuestion + 1}/{questObj.length} </Text>
</View>
<View style={styles.row}>
<Text style={Object.assign(styles.headingColumn)}>{questObj[currentQuestion].questionText}</Text>
</View>
<View style={styles.row}>
{questObj[currentQuestion].answerOptions.map((answerOption: { answerText: string; isCorrect: boolean; }, index: any) => (
<Text style={Object.assign(styles.buttonColumn)}>
<Button
title={answerOption.answerText}
onPress={() => handleAnswerButtonClick(answerOption.isCorrect)}
color="#fff">
</Button>
</Text>
))}
</View>
</View>
: <></>}
</View>;
}