Mapping objects, and using state, and passing value through a function in setState

I have a react application, where i want to set the state equal to an array of objects, that has been passed through a function.

I have two variables, and is the file extension, and one is the raw data base64 encoded.

                       this.setState({
                              result: fileItems.map(fileItem => ({
                                "file": this.findFileTypeHandler(fileItem.file.name), 
                                "data": this.getBase64(fileItem.file)
                              }))
                            });
                      }}>

as of right now i just return the value within the two functions, but the issue occurs, when the functions are not asynchronous.

findFileTypeHandler = file =>{
    return file.split('.').pop();
}

getBase64 = file => {
    //find en måde at gøre den asynkron
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function () {
      console.log(reader.result) 
      this.setState({base64: reader.result})
     return reader.result;
    };
    reader.onerror = function (error) {
      console.log('error is ', error)
    };
  }

the best case scenario, would be to setState, and then assign the value for each map iteration, but how can i pass the data through the functions, and set the state respectivly?

Upvotes: 0

Views: 39

Answers (1)

vedsmith92
vedsmith92

Reputation: 599

How about use Promise.all to wait all files to be read, then setState the results.

Promise.all(
    fileItems.map(fileItem => new Promise((resolve, reject) => {

        //find en måde at gøre den asynkron
        var reader = new FileReader();
        reader.readAsDataURL(fileItem.file);

        reader.onload = () => {
            resolve({
                file: this.findFileTypeHandler(fileItem.file.name),
                data: {
                    base64: reader.result
                }
            });
        };

        reader.onerror = (error) => reject(error);

    }))
)
.then((results) => {

    this.setState({
        result: results
    });

})
.catch((error) => console.log(error));

Upvotes: 2

Related Questions