docs: add example of typing custom useFetch errors (#29253)

This commit is contained in:
Jeel Rupapara 2024-10-08 18:46:51 +05:30 committed by GitHub
parent 3331994f6a
commit 280e5923ea
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -96,6 +96,28 @@ const { data: modules } = await useAPI('/modules')
</script>
```
If you want to customize the type of any error returned, you can also do so:
```ts
import type { FetchError } from 'ofetch'
import type { UseFetchOptions } from 'nuxt/app'
interface CustomError {
message: string
statusCode: number
}
export function useAPI<T>(
url: string | (() => string),
options?: UseFetchOptions<T>,
) {
return useFetch<T, FetchError<CustomError>>(url, {
...options,
$fetch: useNuxtApp().$api
})
}
```
::note
This example demonstrates how to use a custom `useFetch`, but the same structure is identical for a custom `useAsyncData`.
::