1
    fileChangedHandler = event => {
    event.preventDefault();
    event.persist();
    new ImageCompressor(event.target.files[0], {
    quality: .6,
    success(result) {
      this.setState({selectedFile: result})
    },
    error(e) {
      console.log(e.message);
    },
  });
  }

That is the function above and I want to change state after success but I'm getting setState is not a function

and this is how I trigger it:

<input style={{display: 'none'}} type="file" onChange={this.fileChangedHandler} ref={fileInput => this.fileInput = fileInput}/>
<button type='button' onClick={() => this.fileInput.click()} className='col m3 btn' style={{textTransform: 'none'}}>Choose image</button>
Kadiem Alqazzaz
  • 554
  • 1
  • 7
  • 22
  • Possible duplicate of [React this.setState is not a function](https://stackoverflow.com/questions/31045716/react-this-setstate-is-not-a-function) – Tomasz Mularczyk Feb 17 '19 at 10:18
  • Maybe a scope issue? Try binding or using fat arrow definition for the method. – Julian Feb 17 '19 at 10:18

1 Answers1

6

success is regular function that has dynamic this context that is determined by a caller (ImageCompressor).

Since fileChangedHandler method is an arrow, this refers to component class instance that has setState method.

In order to reach lexical this inside success, it should be an arrow:

...
success: (result) => {
  this.setState({selectedFile: result})
},
...
Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • ooh so that's how to convert to arrow functions, thank you so much I was trying to convert it into arrow function but not in this way, anyway thank you so much!!!! – Kadiem Alqazzaz Feb 17 '19 at 10:18