Not reading from state but can read same data from import

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:

<h2>{quizData[0].question}</h2>

Any ideas why I can’t make this work?

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.

<div>
   <h2>{this.state.dataQuestion[0].question}</h2>
 </div>

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:

 state = {
        dataQuestion: quizData,
        currentQuestion: 0,
        answers: {yes: 0, no: 0}
    }

Use componentDidMount when fetching data from an external API. You can read more about the react life cycle methods Here.

Oh, thanks so much, @nibble! This saves me a lot of frustration!