TechTorch

Location:HOME > Technology > content

Technology

Displaying Images from Fetch API Response in JavaScript: A Comprehensive Guide

May 26, 2025Technology3184
How to Display Images from a Fetch API Response in JavaScript Displayi

How to Display Images from a Fetch API Response in JavaScript

Displaying images from a fetch API response in JavaScript involves a few steps. This guide will walk you through the process, including using both async/await and Promises. We will also discuss specific use cases and additional helper functions to make your code more readable.

Step-by-Step Process

Step 1: Fetch the Image Data

Start by fetching the image using the fetch API. This step initiates a request to the specified URL.

const response  await fetch('URL');

Step 2: Check the Response

Ensure the response is successful by checking the response.ok property. If the response is not successful, throw an error to handle the issue gracefully.

if (!response.ok) {    throw new Error('Network response was not ok');}

Step 3: Convert the Response to a Blob

Convert the response to a Blob or ArrayBuffer depending on your needs. A Blob is particularly useful for displaying images since it contains raw data which can be easily converted into a URL.

const blob  await ();

Step 4: Create a URL for the Blob

Create a URL using the (blob) method. This URL can then be used as the src attribute of an img element.

const imageUrl  (blob);

Step 5: Create and Display the Image

Create an img element and set its src attribute to the generated URL. Append the img element to the desired container, such as the document body.

const img  ('img');  imageUrl;(img);

Example: Displaying Randomly Sized Images of KITTENS

To illustrate, we can use a PlaceKitten API to fetch images of kittens with randomized sizes. First, we need some helper functions to assist with random number generation and image URL creation.

// Helper function to generate a random number within a specified rangeconst range10  (min  20, max  50) > Math.random() * (max - min)   min;// Select the body element for displaying the imagesconst kittensDisplay  document.querySelector('body');// Create a function to generate random kitten images with randomized sizesconst infiniteKittens  (width  range10(), height  range10()) > `${width}/${height}`;// Helper function to turn a URL into an IMG elementconst getUrlAsImg  (src) > fetch(src)    .then((response) > ())      .then((blob) > (blob))    .then((src) > {        const img  ('img');          src;        return img;    })    .catch((error) > {        ('Error:', error);        return null;    });// Example usagegetUrlAsImg(infiniteKittens()).then((img) > {    if (img) {        (img);    }});

Using Async/Await

For a more modern approach, we can use async/await to make the code more readable and easier to handle asynchronous operations. Here’s an example using async/await:

// Helper function to create an IMG element from a URL using async/awaitasync function createImgFromUrl(srcUrl) {    const arrayBuffer  await fetch(srcUrl).then((resp) > ());    const img  ('img');      (new Blob([arrayBuffer], { type: 'image/jpeg' }));    return img;}// Example usagecreateImgFromUrl(infiniteKittens()).then((img) > {    if (img) {        (img);    }});

Conclusion

Displaying images from a fetch API response in JavaScript is indeed straightforward. By following the steps outlined in this guide, you can easily integrate image fetching and displaying into your applications. Make sure the URL you are fetching is accessible and that you handle errors gracefully to provide a smooth user experience.