1
votes
type Color = "Blue" | "Red" | null

type Connect4Cell = {
    state: number,
    color: Color
}

type State = {
    gameBoard?: Array<Array<Connect4Cell>>
}

class Game extends React.Component<{||}, State> {

    state = {
        gameBoard: [
            [{}, {}, {}, {}, {}], 
            [{}, {}, {}, {}, {}], 
            [{}, {}, {}, {}, {}], 
            [{state: 1, color: "Blue"}, {state: 1, color: "Red"}, {state: 1, color: "Blue"}, {state: 1, color: "Red"}, {state: 0, color: null}]
        ]
    }

    render() {

        let board = this.state.gameBoard.map<React.Element<any>>(row => <Row />)

        console.log(this.state)
        return (
            <div>
                <p>This line comes from the render of class, Game. </p>
                <table>
                    <tbody>
                        {board}
                    </tbody>
                </table>
                <Cell />
                <Row />
            </div>
        )
    }

}

I can't find out why its giving me this error?

Exact Error Message (on .map):

Cannot call this.state.gameBoard.map because property map is missing in undefined [1].Flow(InferError)

1
By the way, not related to the direct question, but I think that this this.state.gameBoard.map<React.Element<any>>(row => <Row />) should be simply this.state.gameBoard.map(row => <Row />) - frontendgirl

1 Answers

4
votes

The reason why there is in error is, that state is annotated as:

type State = {
    gameBoard?: Array<Array<Connect4Cell>>
}

? sign is saying to flow that this value might be undefined.

As in the example, the initial state is set, and it contains gameBoard in needed shape, change that needs to be done is:

type State = {
    gameBoard: Array<Array<Connect4Cell>>
}

However, if at any time of the component live it is expecting to have gameBoard not set, then the solution will be to add a check before calling .map function as following

let board = this.state.gameBoard ? this.state.gameBoard.map(row => <Row />) : null;