Kadiem Alqazzaz
Kadiem Alqazzaz

Reputation: 659

React setState is not a function

    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>

Upvotes: 1

Views: 54

Answers (1)

Estus Flask
Estus Flask

Reputation: 222493

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})
},
...

Upvotes: 6

Related Questions