Hello, I'm trying to get information from a controller using an async function, I do this in a component:
I need to send parameters because I have seen similar answers with Mounted() but they don't send parameters to the function so if I don't add the parameters it won't work.
View section:
<tbody> <tr v-for="(post, index) in last_month_day" v-bind:index="index"> <td>{{ index 1 }}</td> <td v-for="(post2, index2) in branch_office_posts" v-bind:index="index2"> $ {{ getTotalIncomes(index 1, post2.branch_office_id) }} </td> </tr> </tbody>
I need to pass these two parameters to the function: index 1 and post2.branch_office_id
Then I do this in the method section:
methods: { async TotalIncomeData(day, branch_office_id) { const response = await fetch('/api/collection/total/' day '/' branch_office_id '?api_token=' App.apiToken) return response; }, getTotalIncomes(day, branch_office_id) { return this.TotalIncomeData(day, branch_office_id); },
It works, I mean if you check the response using console.log() it gets a value. I know I can't use the async await function in the view, that's why I use another function to call this function inside which you can see, but I don't know why I don't use it directly in the view, it says:
$ [object Promise]
So it's not showing the value so I want to know why? What's wrong with the code? I really need help, thank you!
You can use the
data
attribute to store the response. The function is then called to make the request, and anything in the UI that is bound to the data will be updated accordingly.The part you're missing is
.then(...)
, which is in thefetch
documentation.For example:
Now, in your UI, check to see if the response has finished returning,
v-if="response"
, and display it if necessary.