I've been attempting to retrieve data from an API whenever a value is updated in a parent component, and then utilize it in a child component. Despite my efforts, none of the methods I tried seem to be working.
Below is a simplified version of my components:
Parent
<template lang="html">
<div id="wrapper">
<h4>My Super Component</h4>
<button v-on:click="setListID">Load another list</button>
<ChildComponent :usernames="usernames"></ChildComponent>
</div>
</template>
<script>
import ChildComponent from "./ChildComponent.vue"
export default {
components: {
ChildComponent
},
data() {
return {
listID: 0,
usernames: undefined,
}
},
watch: {
listID: function(newID) {
this.usernames = getUsernames(newID)
}
},
methods: {
setListID() {
let id = +prompt("Input the list ID");
if (Number.isNaN(id)) {
alert("Please input a valid number");
} else {
this.listID = id;
}
}
},
async mounted() {
this.usernames = await getUsernames(this.listID)
}
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// Simulating an API call
async function getUsernames(listID) {
sleep(200).then(() => {
switch (listID) {
case 0:
return ['Pierre', 'Paul', 'Jaques']
case 1:
return ['Riri', 'Fifi', 'Loulou']
case 2:
return ['Alex', 'Sam', 'Clover']
default:
return []
}
})
}
</script>
Child
<template lang="html">
<p v-for="username in usernames">{{username}}</p>
</template>
<script>
export default {
props: {
usernames: Object
},
}
</script>
The issue I'm facing is that the prop received in the child component is a Promise. Although I attempted to pass an Array, the asynchronous nature of the data fetching function has me stuck as I can't await in the watch.
UPDATE:
I suspect the problem lies within this block of code:
// Simulating an API call
async function getUsernames(listID) {
await sleep(200).then(() => {
switch (listID) {
case 0:
return ['Pierre', 'Paul', 'Jaques']
case 1:
return ['Riri', 'Fifi', 'Loulou']
case 2:
return ['Alex', 'Sam', 'Clover']
default:
return []
}
})
return 'returned too early'
}
Regardless of the listID provided, the function consistently returns 'returned too early'
. Removing this default return results in undefined
being returned, which the child component interprets as an array.