Big Dumb
Big Dumb

Reputation: 120

React not initialising state

While following the basic react tutorial at https://reactjs.org/tutorial/tutorial.html,

I ran into the error TypeError: Cannot read property 'history' of null

After some debugging, localised the error to state not being accessible from other methods.

In index.js

constructor(props) {
        super(props);
        var state = {
            history: [
                {
                    squares: Array(9).fill(null)
                }
            ],
            xIsNext: true
        };
    }
    ...
    render() {
        const history = this.state.history; //Error thrown here
        const current = history[history.length - 1];
        const winner = this.calculateWinner(current.squares);
        let status;
        ...

Upvotes: 0

Views: 32

Answers (1)

Big Dumb
Big Dumb

Reputation: 120

The issue arises from the constructor where state is initialised.

replace

        var state = {
            history: [
                {
                    squares: Array(9).fill(null)
                }
            ],
            xIsNext: true
        };

with

        this.state = {
            history: [
                {
                    squares: Array(9).fill(null)
                }
            ],
            xIsNext: true
        };

Upvotes: 1

Related Questions