Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save wealthfront-data-fetching-blog-post/ce9892d3b20336e8e35a0d63102d50c7 to your computer and use it in GitHub Desktop.
Save wealthfront-data-fetching-blog-post/ce9892d3b20336e8e35a0d63102d50c7 to your computer and use it in GitHub Desktop.
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