1

Link to CodeSandbox example.

I've designed a quick mockup of an image uploader for an app I'm working on, and I'm now using react-cropper as a way to crop the images to adhere to a 1:1 ratio.

TL;DR

I have a method on my Class called cropImage, taken from one of the examples and modified for my needs. Here's what that looks like:

  cropImage() {
    const { images, cropResult } = this.state;
    if (typeof this.cropper.getCroppedCanvas() === "undefined") {
      return;
    }
    this.setState({
      cropResult: this.cropper.getCroppedCanvas().toDataURL(),
      images: [...images, cropResult]
    }, () => {
      console.log(images)
    })
  }

What happens when this method gets called is that the array is updated and printed to the console, but not immediately. What am I missing here? I've tried to use a callback function to update the state immediately but that doesn't seem to work.

Any ideas?

More information

I'm basically trying to push the cropped images to an array, which I will later render to another component (see the flow below to see what I mean).

I assume this is the right way to go about something like this?

Link to CodeSandbox example.

Flow

Not sure if this is relevant, but here's the flow just incase:

enter image description here

a7dc
  • 3,323
  • 7
  • 32
  • 50
  • Hey @MayankShukla, maybe, although as mentioned in the OP I've tried to do what's been recommended there by using a callback method to invoke state change immediately but it hasn't worked. So not sure really, I will try the recommendations in that post again - maybe I was missing something. Will report back – a7dc Aug 31 '17 at 11:19
  • sorry my mistake, misunderstood the question. – Mayank Shukla Aug 31 '17 at 11:27
  • That's ok, I think it's worth mentioning anyway and changing the code to reflect that, because that was my initial thinking too (that I needed to use a callback). – a7dc Aug 31 '17 at 11:28
  • Setstate is called asynchronously - see this answer https://stackoverflow.com/questions/38558200/react-setstate-not-updating-immediately – Duncan Thacker Aug 31 '17 at 11:39
  • Hey @DuncanThacker thank you for your comment. Isn't that already what I'm doing? I've changed the OP to have a callback function called after setState which is what the comments recommended in your linked post, right? – a7dc Aug 31 '17 at 11:52
  • Needed to use `this.state.images` to get the new array! CodePen updated – a7dc Sep 02 '17 at 11:36

0 Answers0