Hiago Bonamelli
Hiago Bonamelli

Reputation: 381

Why not render I can not access the state array?

When I try to access the object in the array in console.log it works, but at the time of displaying on the page does not work, why?

When I use the map it works, but trying to access only one element does not.

State initialized

type State = {
    id_evaluation: string,
    questions: Array<{
        id: number,
        question_content_id: number,
        component: Array<{
            type_desc: string,
            content: string,
        }>,
    }>,
    current_question: number,

};

This work

class Evaluation extends Component < Props, State > {
    state = {
        id_evaluation: '',
        questions: [],
        current_question: 0,
    }

    componentDidMount() {
        const id_eval = getEvaluation();

        this.setState({
            id_evaluation: String(id_eval),
            }, () => api.get("/evaluation/" + this.state.id_evaluation + "/")
                    .then(response => {
                        this.setState({
                            questions: response.data.question
                            });
                            console.log(this.state.questions[0].component[0].content)
                    })
        );
    }

This don't work

render () {
    return (

        <div>
            {this.state.questions[0].component[0].content}
        </div>

    )
}

Upvotes: 0

Views: 38

Answers (2)

Mgolb
Mgolb

Reputation: 51

you asked why does it work, well it works because reacts lets you know the chronicle order of events that happen, and due to that render happens before the "componentDidMount" -source , and take a look at the following lifecycle chart .

Upvotes: 1

Hai Pham
Hai Pham

Reputation: 2225

In initializing state, your this.state.questions is [], so this.state.questions.[0].component[0] will cause an error. Try verifying your array first:

render () {
    return (

        <div>
            {this.state.questions.length > 0 ? this.state.questions.[0].component[0].content : null}
        </div>

    )
}

Upvotes: 0

Related Questions