Created
March 1, 2025 18:18
-
-
Save davidparys/d06fab8d580e301342c124c9191647ea to your computer and use it in GitHub Desktop.
Typed fetch for api routes in nuxt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// composables/useTypedFetch.ts | |
import type { UseFetchOptions } from 'nuxt/app' | |
import type { InternalApi } from 'nitropack' | |
import type { ApiRoutes, ApiResponse } from './apiResponse' | |
export const useTypedFetch = <T extends ApiRoutes, M extends keyof InternalApi[T]>( | |
route: T, | |
method: M, | |
opts?: Omit<UseFetchOptions<ApiResponse<T, M>>, 'method'> | |
) => { | |
return useFetch(route, { | |
...opts, | |
method: method as any, // Type assertion needed due to Nuxt's type constraints | |
transform: (response) => response as ApiResponse<T, M> | |
}) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script setup lang="ts"> | |
const { data, status, error } = useTypedFetch('/api/properties/:id', 'default') | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment