mardi 5 février 2019

Render a loader while files are sended to the server in react.js

I'm sending XML files to the server using react.js and I want to render a loader until the server make a response.

I tried with one file component and it works. But I want to make it with three different files, each one with a different size and response time.

I have something like this.

class UploadFiles extends Component {
  state = { 
  isLoading: null }

 // Omitted code for upload files to the state


 uploadData(file){
 // Omitted Code <- Asynchronous function, each file has a different
                    response time.
 }


  handleSubmit(){

    this.setState({isLoading:true}, () => {
     uploadData(file1).then(res => {
         // Do something with the response
     this.setState({isLoading: false});
    }

    this.setState({isLoading:true}, () => {
     uploadData(file2).then(res => {
         // Do something with the response
     this.setState({isLoading: false});
    }

    this.setState({isLoading:true}, () => {
     uploadData(file3).then(res => {
         // Do something with the response
     this.setState({isLoading: false});
    }


  }

  render() { 
    return (
   const {isLoading} = this.state;
   if(isLoading){
     return <Loader/> 
   }else {
   return (
   <div>
   <FileComponent />
   <FileComponent/>
   <FileComponent/>
   <button onClick={this.handleSubmit.bind(this)}>submit</button>
   </div> );}
  }
}

This kind of works, but if the file1 is uploaded to the server more faster than the other two files the Loader component is not still rendered. I need that the loader is still rendered until the three files are uploaded to the server.

There is some correct/clean way to make this? Note: I need to send the files one by one to the server. The server only receives one file per request.

Aucun commentaire:

Enregistrer un commentaire