As I delved into the world of fetching APIs and displaying their data on a Vue.js3 webpage, I encountered an interesting issue. My goal was to showcase different dog breeds and have a random dog image display when a breed is clicked. However, when I tried calling the function fetchAPI()
, I ran into this error:
https://i.sstatic.net/39RKO.png
Curiously, assigning the function to a variable fun
and then calling that variable resolved the problem and made it work perfectly. But why did that make a difference? Below is the snippet of code causing me all this confusion:
<template>
<div class="dog">
<ul class="dog__ul">
<li class="dog__li" v-for="(value, name) in data.message" :key="name"
@click="fun"
//When using `fetchAPI()` instead of "fun", it throws an error
>
{{ name }}
</li>
</ul>
<img :src="image" alt="dog picture" class="dog__img">
</div>
</template>
<script>
import { ref , onMounted, onUnmounted } from 'vue';
export default {
setup(){
const data = ref({});
let image = ref(null);
let fun = fetchAPI;
function fetchList(){
fetch("https://dog.ceo/api/breeds/list/all")
.then(response => response.json())
.then(info=>data.value = info)
.catch(err => console.log (err.message))
}
function fetchAPI(){
fetch(`https://dog.ceo/api/breeds/image/random`)
.then(response => response.json())
.then(val=>image.value = val.message)
.catch(err => console.log (err.message))
}
onMounted(() => {
console.log ("Mount : DogAPI Mounted ⭕");
fetchAPI();
fetchList();
});
onUnmounted(() => console.log("unMount: DogAPI Unounted ❌ "));
return {
data,
image,
fun,
};
}
};
</script>