user123928
user123928

Reputation: 11

setState in infinite loop inside render

How do I perform the same setState inside map but outside render / avoid the infinite loop that is:

Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested.

class MyComponent {
  render() {
    var images = [
      "https://i.picsum.photos/id/912/500/300.jpg?hmac=m-mTOMKlGcXQHDObNABzzeFPUPMuBVHr2l4rhrGjnmQ",
      "https://i.picsum.photos/id/912/500/300.jpg?hmac=m-mTOMKlGcXQHDObNABzzeFPUPMuBVHr2l4rhrGjnmQ",
      "https://i.picsum.photos/id/912/500/300.jpg?hmac=m-mTOMKlGcXQHDObNABzzeFPUPMuBVHr2l4rhrGjnmQ",
      "",
      "",
    ];
    return (
      <div class="row thumbnailview">
        {images.map((image, index) => {
          if (image.length < 2) {
            return (
              <div className="col thumbnails hidden">
                <img src={image} className="thumbnail" />
              </div>
            );
          }
          if (image.length >= 2) {
            return (
              <div className="col thumbnails">
                <img src={image} className="thumbnail" onClick={this.setState({ imageSrc: { image } })} />
              </div>
            );
          }
        })}
      </div>
    );
  }
}

Upvotes: 1

Views: 293

Answers (2)

AKX
AKX

Reputation: 168841

You're calling setState during render in

onClick={this.setState({imageSrc: {image}})}

What you really want there is

onClick={() => this.setState({imageSrc: {image}})}

i.e. to wrap that setState in a function that only gets called when you click on the image.

Upvotes: 2

Adam Jenkins
Adam Jenkins

Reputation: 55613

Your onClick should look like this:

onClick={() => this.setState({imageSrc:{image}})}

NOT this:

onClick={this.setState({imageSrc: {image}})}

Upvotes: 2

Related Questions