How to Display GIFs from API Response Using JavaScript Fetch

Getting undefined error when accessing GIF data

I’m having trouble working with the Giphy API response. When I log the entire response to the console, everything works fine and I can see all the GIF data. But when I try to access specific properties from the response to display the images, I get an error saying the property is undefined.

const searchForm = document.getElementById("search-form");
searchForm.addEventListener("submit", getAnimatedGifs);

function getAnimatedGifs(event) {
  event.preventDefault();
  const query = document.getElementById("query-input").value;
  fetch(`https://api.giphy.com/v1/gifs/search?q=${query}&limit=50&api_key=YOUR_API_KEY`)
  .then((res) => res.json())
  .then(result => displayGifs(result.data.images.fixed_height.url))
  .catch(error => console.log(error));
}

function displayGifs(imageUrls) {
  const container = document.getElementById("gif-container");
  let html = '<div class="grid">';
  
  imageUrls.forEach((gifUrl) => {
    html += `<img src="${result.data.original.fixed_height_url}" alt="gif"/>`;
  });
  
  html += '</div>';
  container.innerHTML = html;
}
<form id="search-form">
  <input type="text" id="query-input" placeholder="Search for GIFs">
  <button type="submit">Search</button>
</form>
<div id="gif-container"></div>

The error happens when I try to access the nested image properties. Without the display function, the API call works perfectly. What am I doing wrong with the data structure access?

Your code has a couple issues with how you’re handling the response data.

First problem:

.then(result => displayGifs(result.data.images.fixed_height.url))

result.data is an array of GIF objects, not a single object. You’re trying to access images directly on the array instead of individual items.

Second issue: your displayGifs function uses result.data.original.fixed_height_url but result doesn’t exist in that scope, and the property path is wrong.

Here’s the fix:

function getAnimatedGifs(event) {
  event.preventDefault();
  const query = document.getElementById("query-input").value;
  fetch(`https://api.giphy.com/v1/gifs/search?q=${query}&limit=50&api_key=YOUR_API_KEY`)
  .then((res) => res.json())
  .then(result => displayGifs(result.data))
  .catch(error => console.log(error));
}

function displayGifs(gifs) {
  const container = document.getElementById("gif-container");
  let html = '<div class="grid">';
  
  gifs.forEach((gif) => {
    html += `<img src="${gif.images.fixed_height.url}" alt="gif"/>`;
  });
  
  html += '</div>';
  container.innerHTML = html;
}

I ran into this exact thing building a GIF search feature last year. Giphy API returns data as an array, and each item has an images object with different size options like fixed_height, original, etc.