Leon Gaban
Leon Gaban

Reputation: 39028

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?

Upvotes: 1

Views: 7879

Answers (3)

Dan Abramov
Dan Abramov

Reputation: 268255

Aside from the mistake that was already pointed out (you need to return state), your implementation is buggy and won't work correctly.

You are trying to "sync" a prop into the local state. This is a bad idea because any unrelated re-render of a parent component will destroy local state.

It looks like you should completely remove getDerivedStateFromProps, and just use props directly. You don't need local state in this example at all.

For a more in-depth take on why this pattern is broken, and some easy alternatives to it, check out the official React blog post on avoiding deriving state.

Upvotes: 7

Eddie D
Eddie D

Reputation: 1120

You're using this in the context of a static method. Static does not rely on an instance of the class, so the this isn't the same. You're best bet is to return modal in a non static method and then set it from there :D

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

  constructor(props) {
    super(props);

    this.state = {
      modal: {}
    };
    
    SetModalState(modal)
    {
      this.setState(modal)
    }
  }

Upvotes: 1

Jamie Dixon
Jamie Dixon

Reputation: 53991

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 };
  }

Upvotes: 13

Related Questions