Flow: Cannot setState to value that was initially null - type is incompatible

Created on 19 Jul 2016  路  4Comments  路  Source: facebook/flow

There is a modal manager I am transferring to flow in our codebase and it has an initial state -

state = {
  modal: null,
}

When the app changes the state - adds a react element to the modal state value - flow errors with

169:         this.setState({ modal: lastModal });
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ call of method setState
169:         this.setState({ modal: lastModal });
                                    ^^^^^^^^^ React$Element. This type is incompatible with
 27:     modal: null,
                ^^^^ null

The state is typed as follows

state: {
  modal: ?React.Element<any>,
};
Pending clarification react

Most helpful comment

As a workaround, please cast null to the appropriate type, like

state = {
  modal: (null: ?React.Element<any>),
}

Let us know if it doesn't work. Also, where does the above line appear?

All 4 comments

As a workaround, please cast null to the appropriate type, like

state = {
  modal: (null: ?React.Element<any>),
}

Let us know if it doesn't work. Also, where does the above line appear?

@avikchaudhuri that worked, although I don't like having so much boilerplate. Why isn't the state type declaration taking this into context?

Thanks

Any news on that? I stumbled onto this case too, here is a small example. @avikchaudhuri's workaround does work, but is that really normal?

This works as expected in 0.53, it can be closed.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

bennoleslie picture bennoleslie  路  3Comments

mmollaverdi picture mmollaverdi  路  3Comments

ghost picture ghost  路  3Comments

ctrlplusb picture ctrlplusb  路  3Comments

cubika picture cubika  路  3Comments