Search code examples
javascriptreactjsgetderivedstatefromprops

When using getDerivedStateFromProps (React) getting error: Cannot read property 'setState' of null


So just learned that componentWillReceiveProps is deprecated and we need to use getDerivedStateFromProps lifecycle method now. https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops

I'm using it as such below:

class Main extends Component {
  static getDerivedStateFromProps(props) {
    console.log('getDerivedStateFromProps', props);
    const { modal } = props;
    this.setState({ modal });
  }

  constructor(props) {
    super(props);

    this.state = {
      modal: {}
    };
  }

However it errors out on the setState

enter image description here

main.js:30 Uncaught TypeError: Cannot read property 'setState' of null at getDerivedStateFromProps (main.js:30)

What am I missing here?


Solution

  • Because getDerivedStateFromProps is a static function, there is no instance (this).

    Instead, this function is designed so that you return your state rather than using this.setState.

    static getDerivedStateFromProps(props) {
        console.log('getDerivedStateFromProps', props);
        const { modal } = props;
        return { modal };
      }