codeouz
codeouz

Reputation: 63

img src not being set after component mount in vue

i have a component that is being mounted on a v-for loop. The mounted component has a onMount method. the method executes some code to get an img url I have located in firebase and sets the img src with that url. My component gets mounted 3 times and the code executes 3 times but only one image's src gets updated. It gets updated with a random url every time. If i have 3 images in firebase, on every page refresh the img's src changes to a new url eventhough it should have one correct url. The behaviour should be that each component's image src gets updated with the correct image. Any help is appreciated.

Component mount:

<div :key="expert.email" v-for="expert in filteredExperts"> 
    <ExpertCard @openPopup="openPopup" :Expert="expert" class=""/>
</div>

Component Onmount method:

onMounted(async () => {
    const storage = getStorage();
    const ImgRef = Ref(storage, props.Expert.profile_picture);
    await getDownloadURL(ImgRef)
  .then((url) => {
    // Or inserted into an <img> element
    console.log(url)
    const img = document.getElementById('myimg');
    img.setAttribute('src', url);
  })
  .catch((error) => {
    // Handle any errors
  });  

})

Img src:

 <img id="myimg" class="mx-auto rounded w-24 h-24" src="">

Upvotes: 0

Views: 57

Answers (1)

Boris Maslennikov
Boris Maslennikov

Reputation: 360

Lots of img tags with the same id. use :src or ref

+ you need to choose whether to use async/await or Promise

Try this (using :src + Promise):

<template>
    <img :src="profilePicture">
</template>

<script setup>
const profilePicture = ref(null); // you can put placeholder image url here

onMounted(() => {
    const storage = getStorage();
    const ImgRef = Ref(storage, props.Expert.profile_picture);
    getDownloadURL(ImgRef)
  .then((url) => {
    // Or inserted into an <img> element
    console.log(url)
    profilePicture.value = url
  })
  .catch((error) => {
    // Handle any errors
  });  
})
</script>

Upvotes: 0

Related Questions