Created
July 30, 2024 21:42
-
-
Save wealthfront-data-fetching-blog-post/ca5c491063024f1e91ee1a7830043074 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
type UseApiQueryOptions<EndpointName extends ApiEndpointName, Prefetched extends boolean | undefined> = UseQueryOptions< | |
ApiResponse<EndpointName> | |
> & { | |
prefetched?: Prefetched; | |
}; | |
type UseApiQueryData<EndpointName extends ApiEndpointName, Prefetched extends boolean | undefined> = Prefetched extends true | |
? ApiResponse<EndpointName> | |
: ApiResponse<EndpointName> | undefined; | |
function useApiQuery<EndpointName extends ApiEndpointName, Prefetched extends boolean | undefined>( | |
endpointName: EndpointName, | |
params: ApiParams<EndpointName>, | |
options?: UseApiQueryOptions<EndpointName, Prefetched> | |
) { | |
const { onError, ...restOptions } = options ?? {}; | |
const { data: data, ...restQuery } = useQuery({ | |
queryKey: [endpointName, ...params], | |
queryFn: async (): Promise<ApiResponse<EndpointName>> => { | |
return api[endpointName].apply(null, params); | |
}, | |
onError: (error) => { | |
alertErrorMonitoring(error); | |
onError?.(error); | |
}, | |
cacheTime: Infinity, | |
...restOptions, | |
}); | |
return { | |
data: data as UseApiQueryData<EndpointName, Prefetched>, | |
...restQuery, | |
}; | |
} | |
const { data } = useApiQuery('getUser', [123]); | |
// ^ User | undefined | |
const { data } = useApiQuery('getUser', [123], { prefetched: true }); | |
// ^ User |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment