3

I'd like to set a progress bar in my react code:

class imageUpload extends Component {
  constructor(props) {
    super(props);
    this.state = {
      image: null,
      url: '',
      progress: 0
    }

I have progress in my state.

upload = (image) => {
    ImageTools.resize(image, {
        width: 320, // maximum width
        height: 240 // maximum height
    }, function(blob, didItResize) {

        document.getElementById('preview').src = window.URL.createObjectURL(blob);

      const uploadTask = storage.ref(`images/${image.name}`).put(blob);
      uploadTask.on('state_changed', 
      (snapshot) => {
        // progrss function ....
        const progress = Math.round((snapshot.bytesTransferred / snapshot.totalBytes) * 100);
        this.setState({progress}); // Unhandled Rejection (TypeError): Cannot read property 'setState' of undefined
      }, 

when I select an image and upload it, it is going to server, but I get this error: Unhandled Rejection (TypeError): Cannot read property 'setState' of undefined

html

<progress value={this.state.progress} max="100"/>

any ideas why?

thanks!

RGS
  • 4,062
  • 4
  • 31
  • 67

3 Answers3

2

I guess you need to transform your anonymous function function(blob, didItResize){} into an arrow function (blob, didItResize) => {}.

phpguest
  • 786
  • 1
  • 6
  • 16
2

Convert your function expression into an arrow function.

function(blob, didItResize) {

to

(blob, didItResize) => {

To keep this pointing to the right context.

kind user
  • 40,029
  • 7
  • 67
  • 77
2

You need to use arrow function:

(blob, didItResize) => { ... }

instead of

function (blob, didItResize) { ... }
Maycon Mesquita
  • 4,470
  • 2
  • 21
  • 29