With my limited knowledge of vue, I am facing the problem where unless I call an async method within the vue js template I can't access the results of the promise even if I am to call the async method in the created
life cycle hook. My understanding of created
is that it is called earlier so that async operations can be triggered, such as data fetching from an api.
As you'll see in the code below, the function loadAlerts()
is called within created
. However, unless I call {{loadAlerts()}}
in the template I wouldn't be able to use the result of the promise, alerts
, in the li
that directly follows. The problem of calling {{loadAlerts}}
within the template is that [object Promise]
is also displayed on the template. If I remove the {{loadAlerts}}
from the template than non of my alerts will show up.
Shouldn't the call within created
already populate the result of the promise, eg: alerts
? As you'll see in the code below I have commented out {{loadAlerts()}}
right before looping through the alerts. Without it I don't see any alerts.
What do I need to do so
alerts
will still be populated without needing to callloadAlerts
within the template (ie, call it withincreated
ormounted
instead)
OR
alerts
will still be populated but[object Promise]
is not displayed
I am guessing, option 1 is probably more elegant and the recommended way?
<template>
<div v-if="alerts">
<h4>{{ title }}</h4>
<!-- {{loadAlerts()}} -->
<li v-for="alert in alerts" class="alert">
{{ alert.name }}
</li>
</div>
</template>
export default {
data () {
return {
alerts: null
}
},
computed: {
...mapGetters('authentication', ['token']),
...mapGetters('user', ['profile']),
title () {
// Handle the null case
const alerts = this.alerts || []
return `My Alerts (${alerts.length})`
}
},
methods: {
// This needs to be in the methods, not a computed property
loadAlerts () {
return getUserAlert({
user_id: this.profile.user_id,
token: this.token
}).then(response => (this.alerts = response.data)).catch(
error => console.log(error)
)
}
},
// Initiate loading in a hook, not via the template
created () {
this.loadAlerts()
}
}
</script>