ReactFix
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • React
  • React Native
  • Programming
  • Object Oriented Programming

Friday, November 25, 2022

[FIXED] How to resolve problem with adding blobs into array by getting them from the promise?

 November 25, 2022     blob, javascript, reactjs, typescript, url   

Issue

I have an array of image paths, and I need to convert it to array of blobs:

I use a function:

const pathToBlob = async (url: string) => {
    return await fetch(url).then(r => r.blob())
        .then(blobFile => new File([blobFile],
            "fileNameGoesHere", {type: "image/png"})
        )
}

Then I'm trying to use it:

let blobs:any = []

if (vehicle.images) {
    for (let i of vehicle.images) {
        //@ts-ignore (cant type i into loop)
        const file = pathToBlob(process.env.REACT_APP_API_URL+i.img)
        blobs=[blobs,...file] // error
        console.log(file) //    [[Prototype]]: Promise [[PromiseState]]: "fulfilled [[PromiseResult]]: File
    }
    console.log(blobs)
}

But I'm recieving a Promise with:

[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: File

Otherwise Into function (if I refactor to const file = await.... console.log(file)) I'm getting a ready blob.


Solution

Try this, I added an async iife to get an async context since I don't from where you are running this. This is needed to be able to use await.

const pathToBlob = async (url: string) => {
    const blob = await fetch(url).then(r => r.blob());
    return new File([blob], "fileNameGoesHere", { type: "image/png" });
}

(async () => {
    const blobs: Array<File> = await Promise.all(
        vehicle.images.map(async (image: any) => {
            return pathToBlob(process.env.REACT_APP_API_URL+image.img);
        }),
    );

    console.log({ blobs }); 
})();


Answered By - Axekan
Answer Checked By - - David Marino (ReactFix Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post Home

Featured Post

Is Learning React Difficult?

React is difficult to learn, no ifs and buts. React isn't inherently difficult to learn. It's a framework that's different from ...

Total Pageviews

Copyright © ReactFix