Home > Enterprise >  React - Uncaught TypeError: Cannot read properties of undefined (reading 'setState')
React - Uncaught TypeError: Cannot read properties of undefined (reading 'setState')

Time:01-31

I'm not able to setState inside my callback function to be able to get the progress percentage of my S3 upload.

What I'm trying to do is to choose a file from pc, upload it to S3 and render it in my dom with a progress bar.

class Dashboard extends React.Component {
    constructor(props) {
        super(props);
        this.state = { uri: "", uploadProgress : 0 };
    }

    async onChange(e) {
        const file = e.target.files[0];

        //upload to S3, works great
        try {
            await Storage.put(file.name, file, {
                progressCallback(progress) {
                    const prog = parseInt(progress.loaded/progress.total*100)
                    console.log(prog "%");
                    //undefined
                    this.setState({uploadProgress: prog})
                },
                contentType: file.type, // contentType is optional
            });
        } catch (error) {
            console.log("Error uploading file: ", error);
        }

        //get from S3, works but not the setState
        try {
            const amen = await Storage.get(file.name, { expires: 60 });

            this.setState({
                uri: amen
            })

        } catch (error) {
            console.log("Error file: ", error);
        }

    }

    render() {
        return (
            <div>
                <input type= "file" onChange = { this.onChange } />
                <img src={this.state.uri}/>
                {this.state.uploadProgress && <ProgressBar now={this.state.uploadProgress} label={this.state.uploadProgress   "%"} />}
            </div>
        )
    }
}

Everything works except this:

this.setState({uploadProgress: prog})

I don't understand why I'm unable to call my state progress, what's wrong?

CodePudding user response:

You are calling the this keyword from a different execution context. The this in your progressCallback searches for a method called setState in its local execution context but cannot find it.

As this related answer describes it, you can reference the proper this by changing your code like so:


 async onChange(e) {
      const baseThis = this;
        const file = e.target.files[0];

        try {


            await Storage.put(file.name, file, {
                progressCallback(progress) {
                    const prog = parseInt(progress.loaded/progress.total*100)
                    console.log(prog "%");
                    baseThis.setState({uploadProgress: prog})
                },
                contentType: file.type, // contentType is optional
            });
        } catch (error) {
            console.log("Error uploading file: ", error);
        }


// other things

}
  •  Tags:  
  • Related