Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeatedly calling setState inside componentWillUpdate or componentDidUpdate?

I'm trying to figure out the orientation of background-images in a React component that are passed in as props.

I start off by creating an Image object and setting its src to the new Image:

  getImage() {
    const src = this.props.url;
    const image = new Image();
    image.src = src;

    this.setState({
      height: image.height,
      width: image.width
    });
  }

After I've updated the state with the heights and widths, I try calling getOrientation() inside of componentDidUpdate():

  getOrientation() {
    const { height, width } = this.state;
    if (height > width) {
      this.setState({ orientation: "portrait" });
    } else {
      this.setState({ orientation: "landscape" });
    }
  }

I then get the following error:

Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate.

Any ideas what's going on here?

Link to Sandbox

like image 208
A7DC Avatar asked Nov 21 '18 23:11

A7DC


Video Answer


1 Answers

You need to include prevProps like so:

componentDidUpdate(prevProps, prevState) {
  ...
}

For more see here.

like image 145
Colin Ricardo Avatar answered Sep 24 '22 05:09

Colin Ricardo