0

I was experimenting with React State where one of the states is an array and I am trying to access one of the individual array elements. I found the line below problematic:

const Character = this.state.Characters[0];

If I use the above line in the code below, React would return error, however if I use:

const Character = somedefinedarray[0];

The below codes would work, but I could not see the difference for the two lines above at all. Can anyone enlighten me somehow? Might it be something related to "this" or state array access or so???

class Ch extends Component {
    constructor(props) {
        super(props);
        this.state = {
            Characters: []
        }
    }
    componentDidMount() {
        this.setState({Characters: somedefinedarray});
    }
    render() {
        const Character = this.state.Characters[0];
        return (
            <p>{Character.somestate}</p>
        )
    }
}

1 Answer 1

1

During your first render, your default state is Characters: [].

So, when you access Character = this.state.Characters[0];, Character will be undefined because your state array is empty.

Then, you try to use Character.somestate which will result in an error saying, cannot read property somestate of undefined.

Sign up to request clarification or add additional context in comments.

1 Comment

@BhojendraRauniyar accessing a non existent index of an array doesn't throw an error. It just returns undefined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.