I’m using React to make a little quiz for an app . The first step is to show the quiz questions on the screen. Here’s what I have so far:
quizData .js
– a file with const quizData = [{id: “1”, question: “have you ever…?”}, {id: “2”… and so forth
Quiz.js
–a class-based component.
–quizData is imported
–the data is put into this.state.dataQuestion (I’ve verified this works correctly because I can see it in React Dev Tools).
But when I try to render stuff from dataQuestion, using the following expression, <h2>{this.state.dataQuestion[0].question}</h2>
I get this: TypeError: Cannot read property 'question' of undefined
whereas I can access the imported data directly:
Hi @CactusWren2020. The problem is you are setting state in componentDidMount life cycle method.
componentDidMount() {
this.setStateFunction();
}
React invokes componentDidMount after render has been invoked. So by the time you set the value of dataQuestion to quizData, the line below which is inside render would have been executed.
Since you have initially set this.state.dataQuestion to an empty array [], this.state.dataQuestion[0] is undefined. Therefore undefined.question will throw an error. Try assigning the imported data as below: