Search code examples
vue.jsvuejs2

why the photos are not displaying


Problem Statement:
I have a Vue component that should display random cat images fetched from https://cataas.com/cat. The component structure is straightforward, iterating over an array (catImageUrls) containing image URLs and binding them to elements using Vue's v-for directive. Despite fetching data successfully from the API, the images are not showing up on the page.

What I've Tried:
Verified network requests in the browser's developer tools; confirmed that requests to https://cataas.com/cat are successful. Checked that response.data from Axios contains valid image URLs. Ensured that Vue.js is properly binding imageUrl to the src attribute of <img> elements within the v-for loop. Expected Outcome: I expect the application to display a grid of cat images upon page load and when clicking the "Load More Cat Images" button.

Actual Outcome:
No images are displayed on the page, despite no errors being logged in the console.

Request for Help:
Could someone please assist in identifying why the images aren't displaying correctly? Any insights into what might be going wrong or suggestions for troubleshooting would be greatly appreciated.

<div id="app">
    <div id="imageContainer">
      <div v-for="(imageUrl, index) in catImageUrls" :key="index" class="cat-image-container">
        <img :src="imageUrl" alt="Cat Image">
      </div>
    </div>
    <button @click="loadMoreCatImages">Load More Cat Images</button>
</div>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      catImageUrls: [],
      numImagesPerLoad: 10,
    },
    methods: {
      loadCatImages(count) {
        for (let i = 0; i < count; i++) {
          axios.get('https://cataas.com/cat')
            .then(response => {
              const imageUrl = response.data; // Assuming response.data directly contains image URL
              this.catImageUrls.push(imageUrl);
            })
            .catch(error => console.error(error));
        }
      },
      loadMoreCatImages() {
        this.loadCatImages(this.numImagesPerLoad);
      }
    },
    mounted() {
      this.loadCatImages(this.numImagesPerLoad);
    }
  });
</script>

Solution

  • The response returned is actually a blob. I think you need to at least configure axios with { responseType: 'blob' } but in my testing I could not get it to work with this specific API. It works fine when processed with fetch though:

    fetch('https://cataas.com/cat')
    .then(response => {
      response.blob().then(myBlob => {
        const imageUrl = URL.createObjectURL(myBlob);
        this.catImageUrls.push(imageUrl);
      })
    })