reactjsasync-awaitfetchsetstatetobase64string

for loop fetch api call and store responses in an state array reactjs


getTarget(filepath){
 const filepaths = [target1, target2, target3, target4]

 for (var i =0; i< filepaths.length; i++){
   var filepath = filepaths[i]
   fetch(filepath)
      .then((response) => response.blob())
      .then(data => { 
        var reader = new FileReader();
        reader.readAsDataURL(data); 
        reader.onloadend = (event)=> {
            var base64data = reader.result;
            this.setState(prevState => ({
               targetlist: prevState.targetlist.concat(base64data)
            }))           
        }
      });
    }

Target 1-4 are images that I have to convert into base64 and stored in the web app in ordered array. I am able to store the 4 images into the targetlist state. However, the order will be all jumbled up. How do I ensure that the list will not be jumbled up from the different time that the responses return?

Or is there a better method that I am able to get the base64 string. The images are stored in local memory.


Solution

  • You can use async/await like this

    async function getTarget(filepath) {
     const filepaths = [target1, target2, target3, target4]
     for (let i =0; i< filepaths.length; i+=1){
       const filepath = filepaths[i]
       const data = await (await fetch(filepath)).blob();
       const reader = new FileReader();
       reader.readAsDataURL(data); 
       reader.onloadend = (event) => {
            const base64data = reader.result;
            this.setState(prevState => ({
               targetlist: prevState.targetlist.concat(base64data)
            }))
       }
     }
    }