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

–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,

I get this:
TypeError: Cannot read property 'question' of undefined
whereas I can access the imported data directly:


Any ideas why I can’t make this work?

Hi @CactusWren2020. The problem is you are setting state in componentDidMount life cycle method.

componentDidMount() {

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:

 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!