Skip to content

Instantly share code, notes, and snippets.

View wealthfront-data-fetching-blog-post's full-sized avatar

wealthfront-data-fetching-blog-post

View GitHub Profile
function Component() {
const { data, isLoading, isError } = useApiQuery('getUser', [userId], { suspense: true });
// can assume data is populated at the top level!
return /* ... */
}
function Wrapper() {
return (
<FetchApiQuery
endpointName="getUser"
params={[userId]}
loadingState={<Spinner />}
>
{({ data }) => {
// data is populated in this function!
}}
</FetchApiQuery>
function Component() {
const { data, isLoading, isError } = useApiQuery('getUser', [userId]);
function renderContent() {
// can assume data is populated in this function!
}
return (
<AsyncStatus
isLoading={isLoading}
// simplified
export function AsyncStatus({
children,
customErrorState,
isError,
isLoading,
loadingState
}) {
if (isLoading) {
return loadingState;
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;
interface User {
name: string;
}
// the fake API SDK from earlier
const api = {
getUser: (userId: number) => {
return new Promise<User>((resolve) => {
resolve({
name: 'Elan',
const { data: queryData } = useQuery({
queryKey: ['getUser', userId],
queryFn: () => api.getUser(userId),
onError: (e) => {
alertErrorMonitoring(e);
},
});
// vs
// simplified
function useApiQuery(endpointName, params, options) {
const { onError, ...restOptions } = options ?? {};
return useQuery({
queryKey: [endpointName, ...params],
queryFn: () => {
return api[endpointName].apply(null, params);
},
onError: (e) => {
interface User {
name: string;
}
const api = {
getUser: (userId: number) => {
return new Promise<User>((resolve) => {
resolve({
name: 'Elan',
});
// https://tanstack.com/query/v4/docs/framework/react/overview
const { data, isLoading, isError } = useQuery({
queryKey: ['repoData'],
queryFn: () => {
return fetch('https://api.github.com/repos/TanStack/query').then((res) => res.json())
},
});