Search code examples
javascriptreactjsprogress-barprogress

how to show progress value in React


this image after set state progressI try to use progress bar to show percentage while uploading image but is not working (it's only show on console.log())

fileuploadHandler = () => {
const storageRef = fire.storage().ref();
this.state.file.forEach((file) => {
  this.setState({ uploading: true })
  storageRef
    .child(`images/${file.name}`)
    .put(file).then((snapshot) => {
      var uploadTask = storageRef.child(`images/${file.name}`).put(file);
    uploadTask.on('state_changed', function(snapshot){
      var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
      this.setState({progress});
      console.log('Upload is ' + progress + '% done');
      switch (snapshot.state) {
        case fire.storage.TaskState.PAUSED: // or 'paused'
          console.log('Upload is paused');
          break;
        case fire.storage.TaskState.RUNNING: // or 'running'
          console.log('Upload is running');
          break;
      }

and

<div className='container'>
      {this.state.uploading
        ? <div>
          <div className='load-bar' />
          <progress   value = {this.state.progress} min = "0" max="100" id="uploader">0%</progress>
          <br/><br/>
          <span>Uploading: {this.state.uploader}%</span>
          <h3> {this.state.progress} </h3>


        </div>

Solution

  • You missed setState statement.You need to update the state of progress with every update.

      var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
        this.setState({progress});//add this one
    

    As no state value update for progress,its not showing on UI.

    EDIT:

    set initial value for progress to 0

    this.state = {
        progress : 0
      }
    

    EDIT 2:

    uploadTask.on('state_changed',(snapshot)=>{