I've writen multiple composables that will fetch specific objects from an API which I use in a component. I need to associate objects from one composable with objects in another composable. However I want to keep the fetch in the composables async so that the component is not waiting on the first to complete before starting the second.
The problem occurs when the API queries have not yet completed and values are not yet set, but the component tries to iterate over their values.
How can I accomplish this task?
The code I have sofar is as follows:
Component code:
const { customers } = useCustomers()
const { datacenters } = useDatacenters()
for (let customer of customers.value) {
customer.datacenters = datacenters.filter(datacenter => datacenter.customer === customer.id)
}
Composable code:
function useCustomers() {
const customers = ref([])
async function updateCustomers(){
customers.value = (await api.get("customers")).json
}
onMounted(() => {
void updateCustomers()
})
return {
customers,
updateCustomers,
}
}
function useDatacenters() {
const datacenters = ref([])
async function updateDatacenters() {
datacenters.value = (await api.get("datacenter")).json
}
onMounted(() => {
void updateDatacenters()
})
return {
datacenters,
updateDatacenters
}
}
null(you can also provideloadedrefs from the composables likecustomersLoaded).watchLoaded(). A bonus would be to make it async:VUE SFC PLAYGROUND