Search code examples
reactjsreact-image-crop

Maximum update depth exceeded error, React-image-crop


I'm using React-image-crop to select area of interest of an image, but I need to read the preset crop dimensions from props at first, so that the cropped area is selected when the image is open. I'm using componentDidMount() to update the crop in state. But it is not working and I got an error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

class Image extends Component<ImagePropsType, ImageStateType>{
  constructor(props: ImagePropsType) {
  super(props);
    this.state = {
      crop: { unit: 'px', y: 0, x: 0, width: 0, height: 0 },
      ...
    }
  }

  componentDidMount() {
    this.setState({
        crop: props.props.presetCrop  // { unit: 'px', y: 10, x: 30, width: 50, height: 90 }
    })
  }
  
  updateCrop = (crop: { unit: string, x: number, y: number, width: number, height: number }) => {
    this.setState({ crop: crop })
  }
  ...
  render() {
    return (
       <ReactCrop src={this.state.imageURL} crop={this.state.crop} onChange={(newCrop) => this.updateCrop(newCrop)} keepSelection />
    )
  }

}

I have also tried updating the crop in state with getDerivedStateFromProps but I got the same error with it. Where did I do wrong? Thank you!


Solution

  • Your Image component works fine without any error: see it live (As you can see in the logs, there number of updates is limited. so it doesn't have the issue you mentioned.)

    So the problem is probably on the parent component of it, or with redux configuration, or on another place.

    Maximum update depth exceeded.

    This happens when you set state on every update. for example by using this handler: onChange={this.updateCrop(newCrop)} instead of : onChange={newCrop => this.updateCrop(newCrop)}

    (The first one calls the onChange on each render, and onChange will cause a new render, so it will become an infinite loop.)