Fetch image from API

The response from the server is an image file, not JSON formatted text.
You’ll want to read the response content with Response.blob(), blob meaning “binary large object”.

In this function we fetch a blob:

async function fetchBlob(url) {
    const response = await fetch(url);

    // Here is the significant part 
    // returning a blob instead of json
    return response.blob();
}

Then, you can create an object URL and assign the source of an image to this generated URL in your React application:

const [imageSourceUrl, setImageSourceUrl] = useState("");

const downloadImageAndSetSource = async (imageUrl) => {
    const image = await fetchBlob(imageUrl);
    setImageSourceUrl(URL.createObjectURL(image));
}

Leave a Comment