Search code examples
vue.jsasync-awaitpromisevuejs3state

Vue How to return value from async/await function in a computed


I have a vue js searchbar when i type in the input bar it needs to show results based on the matching characters

For getting the data I'm using async await function to wait for the api response but it's in computed so it returns a promise so it can't identify it but when i print it shows the correct data but it's not shown in the ui

<template>
 <li v-for="name in names">
      {{ name }}
    </li>
<template>
<script>
export default{
computed: {
  async filteredNames() {
return await apicall();
  }
}}</script>

Solution

  • If the filtering is happening in the component, you don't need to call the API every time when you are filtering the results. Save the API data in the component, and return the filtered results from local data:

    <template>
     <input v-model="filterText">
     <li v-for="name in filteredItems">
        {{ name }}
     </li>
    <template>
    
    <script>
      export default{
        data(){
          return {
            allItems: [],
            filterText: ""
          }
        },
        computed: {
          filteredItems() {
              return this.allItems.filter(item => item.includes(this.filterText))
          }
        },
        mounted(){
          callApi().then(res => {
              this.allItems = res.data
          })
        }
      }
    </script>