Home > Mobile >  how to rewrite composable that get data from API with async await
how to rewrite composable that get data from API with async await

Time:01-04

I'm using composable to get data from API

composable/category.ts

import { useHttp } from './Http'
import type { ICategory } from '@/models/category.model'

export const useCategory = () => {
  const categories = ref<ICategory[]>([])
  useHttp().get('/category').then((res) => categories.value = res.data)
  return { categories }
}

someComponent.vue

import { useCategory } from '@/composables/Category'
const { categories } = useCategory()

this codes work perfectly , the only problem is when I try to rewrite my code with Async await and try catch some error happens

import { useHttp } from './Http'
import type { ICategory } from '@/models/category.model'

export const useCategory = async () => {
  const categories = ref<ICategory[]>([])
  async function get() {
    const res = await useHttp().get('/category')
    categories.value = res.data
  }
  onMounted(async () => {
    get()
  })
  return { categories }
}

enter image description here

Property 'categories' does not exist on type 'Promise<{ categories: Ref<{ _id: string; title: string; }[]>; }>'.ts(2339)

How can I rewrite that composable with async/await and try/catch ?

CodePudding user response:

The error speaks for itself. Your function returns a Promise<{ categories: Ref<...> }>, not a { categories: Ref<...>}. So you need to await it when using like so:

const { categories } = await useCategory()

Or you can remove the async annotation in the function because there is no await inside it.

export const useCategory = () => {
  const categories = ref<ICategory[]>([])
  async function get() {
    try {
        const res = await useHttp().get('/category')
        categories.value = res.data
    }
    catch(err){
        // Do something with the err
    }
  }
  onMounted(() => {
    get()
  })
  return { categories }
}
  • Related