Created
July 30, 2024 21:42
-
-
Save wealthfront-data-fetching-blog-post/ce9892d3b20336e8e35a0d63102d50c7 to your computer and use it in GitHub Desktop.
This file contains 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
interface User { | |
name: string; | |
} | |
// the fake API SDK from earlier | |
const api = { | |
getUser: (userId: number) => { | |
return new Promise<User>((resolve) => { | |
resolve({ | |
name: 'Elan', | |
}); | |
}); | |
}, | |
}; | |
type Api = typeof api; | |
type ApiEndpointName = keyof Api; | |
type ApiResponse<EndpointName extends ApiEndpointName> = Awaited<ReturnType<Api[EndpointName]>>; | |
type ApiParams<EndpointName extends ApiEndpointName> = Parameters<Api[EndpointName]>; | |
function useApiQuery<EndpointName extends ApiEndpointName>( | |
endpointName: EndpointName, | |
params: ApiParams<EndpointName>, | |
options?: UseQueryOptions<ApiResponse<EndpointName>> | |
) { | |
const { onError, ...restOptions } = options ?? {}; | |
return useQuery({ | |
queryKey: [endpointName, ...params], | |
queryFn: (): Promise<ApiResponse<EndpointName>> => { | |
return api[endpointName].apply(null, params); | |
}, | |
onError: (error) => { | |
alertErrorMonitoring(error); | |
onError?.(error); | |
}, | |
...restOptions, | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment