Skip to content

Commit

Permalink
stop using the suspense option on tanstack query
Browse files Browse the repository at this point in the history
client

Signed-off-by: Marc MacLeod <marbemac+gh@gmail.com>
  • Loading branch information
marbemac committed Sep 24, 2024
1 parent 7aee8d6 commit da6fec0
Show file tree
Hide file tree
Showing 19 changed files with 93 additions and 35 deletions.
7 changes: 7 additions & 0 deletions .changeset/healthy-tools-remember.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@ssrx/plugin-tanstack-query': minor
'@ssrx/trpc-react-query': minor
---

Per tanstack query recommendations, stop using the suspense: true option by default. Thus you must change your
.useQuery() instances to .useSuspenseQuery() if you would like to preserve the SSR data fetching.
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ import { TRPCError } from '@trpc/server';
import { desc, eq, or } from 'drizzle-orm';
import { object, omit, parse, partial, pick } from 'valibot';

import { sleep } from '~/utils.ts';
import { createDbId } from '~/api/db/ids.ts';
import { articles, insertArticleSchema, selectArticleSchema } from '~/api/db/schema/index.ts';
import { sleep } from '~/utils.ts';

import { protectedProcedure, publicProcedure, router } from './trpc.ts';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export const ActionBar = ({
trailingActions?: React.ReactNode;
}) => {
const navigate = useNavigate();
const { data } = ctx.trpc.auth.me.useQuery();
const { data } = ctx.trpc.auth.me.useSuspenseQuery();
if (!data) return null;

return (
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import type { UseQueryResult } from '@tanstack/react-query';
import type { UseQueryResult, UseSuspenseQueryResult } from '@tanstack/react-query';
import { type ReactNode, Suspense, useCallback } from 'react';
import { ErrorBoundary, type FallbackProps } from 'react-error-boundary';

export type QueryBoundaryProps<T = unknown> = {
query: () => UseQueryResult<T, unknown>;
query: () => UseQueryResult<T, unknown> | UseSuspenseQueryResult<T, unknown>;

/**
* Triggered when the data is initially loading.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export function Component() {
return (
<QueryBoundary
loadingFallback={<div className="text-muted-foreground">Loading article (with simulated latency)...</div>}
query={() => ctx.trpc.articles.byId.useQuery({ id: articleId! })}
query={() => ctx.trpc.articles.byId.useSuspenseQuery({ id: articleId! })}
>
{data => <Article article={data} />}
</QueryBoundary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export function Component() {
return (
<QueryBoundary
loadingFallback={<div className="text-muted-foreground">Loading article (with simulated latency)...</div>}
query={() => ctx.trpc.articles.byId.useQuery({ id: articleId! })}
query={() => ctx.trpc.articles.byId.useSuspenseQuery({ id: articleId! })}
>
{data => <Article article={data} />}
</QueryBoundary>
Expand Down
2 changes: 1 addition & 1 deletion examples/react-router-kitchen-sink/src/routes/articles.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export function Component() {
<div className="flex divide-x flex-1">
<div className="flex-1">
<QueryBoundary
query={() => ctx.trpc.articles.list.useQuery()}
query={() => ctx.trpc.articles.list.useSuspenseQuery()}
loadingFallback={
<div className="p-10 text-muted-foreground">Loading articles (with simulated latency)...</div>
}
Expand Down
6 changes: 3 additions & 3 deletions examples/react-router-kitchen-sink/src/routes/root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export function Component() {
const AddArticleButton = ({ onSuccess }: { onSuccess?: (article: RouterOutputs['articles']['create']) => void }) => {
const { toast } = useToast();

const { data } = ctx.trpc.auth.me.useQuery();
const { data } = ctx.trpc.auth.me.useSuspenseQuery();
const isLoggedIn = !!data;

const mut = ctx.trpc.articles.create.useMutation({
Expand Down Expand Up @@ -125,7 +125,7 @@ const AddArticleButton = ({ onSuccess }: { onSuccess?: (article: RouterOutputs['
};

const LoginButton = () => {
const { data, isLoading } = ctx.trpc.auth.me.useQuery();
const { data, isLoading } = ctx.trpc.auth.me.useSuspenseQuery();
const login = ctx.trpc.auth.login.useMutation({
onSuccess: () => {
// invalidate the entire query cache on login/logout
Expand Down Expand Up @@ -156,7 +156,7 @@ const LoginButton = () => {
};

const LogoutButton = () => {
const { data } = ctx.trpc.auth.me.useQuery();
const { data } = ctx.trpc.auth.me.useSuspenseQuery();
const logout = ctx.trpc.auth.logout.useMutation({
onSuccess: () => {
// invalidate the entire query cache on login/logout
Expand Down
4 changes: 2 additions & 2 deletions examples/react-router-kitchen-sink/src/routes/wait.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useQuery } from '@tanstack/react-query';
import { useSuspenseQuery } from '@tanstack/react-query';
import { Suspense } from 'react';

import { Counter } from '~/components/counter.tsx';
Expand Down Expand Up @@ -66,7 +66,7 @@ export function Component() {
}

function useWaitQuery(props: { wait: number; deferStream?: boolean; simulateErrorOnServer?: boolean }) {
const query = useQuery({
const query = useSuspenseQuery({
queryKey: ['wait', props.wait, props.simulateErrorOnServer],
meta: { deferStream: props.deferStream },
queryFn: async () => {
Expand Down
2 changes: 1 addition & 1 deletion examples/remix-vite/app/components/article-action-bar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export const ActionBar = ({
trailingActions?: React.ReactNode;
}) => {
const navigate = useNavigate();
const { data } = ctx.trpc.auth.me.useQuery();
const { data } = ctx.trpc.auth.me.useSuspenseQuery();
if (!data) return null;

return (
Expand Down
4 changes: 2 additions & 2 deletions examples/remix-vite/app/components/query-boundary.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import type { UseQueryResult } from '@tanstack/react-query';
import type { UseQueryResult, UseSuspenseQueryResult } from '@tanstack/react-query';
import { type ReactNode, Suspense, useCallback } from 'react';
import { ErrorBoundary, type FallbackProps } from 'react-error-boundary';

export type QueryBoundaryProps<T = unknown> = {
query: () => UseQueryResult<T, unknown>;
query: () => UseQueryResult<T, unknown> | UseSuspenseQueryResult<T, unknown>;

/**
* Triggered when the data is initially loading.
Expand Down
6 changes: 3 additions & 3 deletions examples/remix-vite/app/root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ const AppContainer = () => {
const AddArticleButton = ({ onSuccess }: { onSuccess?: (article: RouterOutputs['articles']['create']) => void }) => {
const { toast } = useToast();

const { data } = ctx.trpc.auth.me.useQuery();
const { data } = ctx.trpc.auth.me.useSuspenseQuery();
const isLoggedIn = !!data;

const mut = ctx.trpc.articles.create.useMutation({
Expand Down Expand Up @@ -125,7 +125,7 @@ const AddArticleButton = ({ onSuccess }: { onSuccess?: (article: RouterOutputs['
};

const LoginButton = () => {
const { data, isLoading } = ctx.trpc.auth.me.useQuery();
const { data, isLoading } = ctx.trpc.auth.me.useSuspenseQuery();
const login = ctx.trpc.auth.login.useMutation({
onSuccess: () => {
// invalidate the entire query cache on login/logout
Expand Down Expand Up @@ -156,7 +156,7 @@ const LoginButton = () => {
};

const LogoutButton = () => {
const { data } = ctx.trpc.auth.me.useQuery();
const { data } = ctx.trpc.auth.me.useSuspenseQuery();
const logout = ctx.trpc.auth.logout.useMutation({
onSuccess: () => {
// invalidate the entire query cache on login/logout
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export default function Component() {
return (
<QueryBoundary
loadingFallback={<div className="text-muted-foreground">Loading article (with simulated latency)...</div>}
query={() => ctx.trpc.articles.byId.useQuery({ id: articleId! })}
query={() => ctx.trpc.articles.byId.useSuspenseQuery({ id: articleId! })}
>
{data => <Article article={data} />}
</QueryBoundary>
Expand Down
2 changes: 1 addition & 1 deletion examples/remix-vite/app/routes/articles.$articleId.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export default function ArticlePage() {
<div>
<QueryBoundary
loadingFallback={<div className="text-muted-foreground">Loading article (with simulated latency)...</div>}
query={() => ctx.trpc.articles.byId.useQuery({ id: articleId! })}
query={() => ctx.trpc.articles.byId.useSuspenseQuery({ id: articleId! })}
>
{data => <Article article={data} />}
</QueryBoundary>
Expand Down
2 changes: 1 addition & 1 deletion examples/remix-vite/app/routes/articles.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export default function Articles() {
<div className="flex divide-x flex-1">
<div className="flex-1">
<QueryBoundary
query={() => ctx.trpc.articles.list.useQuery()}
query={() => ctx.trpc.articles.list.useSuspenseQuery()}
loadingFallback={
<div className="p-10 text-muted-foreground">Loading articles (with simulated latency)...</div>
}
Expand Down
10 changes: 1 addition & 9 deletions packages/plugin-tanstack-query/src/query-client.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { deepmerge } from '@ssrx/renderer';
import { QueryCache, QueryClient, type QueryClientConfig } from '@tanstack/query-core';

type CreateQueryClientOpts = {
Expand All @@ -24,14 +23,7 @@ export const createQueryClient = ({ trackedQueries, blockingQueries, clientConfi

const queryClient: QueryClient = new QueryClient({
queryCache,
defaultOptions: deepmerge(
{
queries: {
suspense: true,
},
},
clientConfig?.defaultOptions || {},
),
defaultOptions: clientConfig?.defaultOptions || {},
});

if (trackedQueries && import.meta.env.SSR) {
Expand Down
40 changes: 37 additions & 3 deletions packages/trpc-react-query/src/createHooksInternal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import {
type UseMutationResult,
useQuery as __useQuery,
type UseQueryResult,
useSuspenseQuery as __useSuspenseQuery,
type UseSuspenseQueryResult,
} from '@tanstack/react-query';
import { type TRPCClientErrorLike } from '@trpc/client';
import type {
Expand All @@ -33,6 +35,7 @@ import type {
UseTRPCInfiniteQueryOptions,
UseTRPCMutationOptions,
UseTRPCQueryOptions,
UseTRPCSuspenseQueryOptions,
} from './types.ts';

export interface UseTRPCSubscriptionOptions<TOutput, TError> {
Expand Down Expand Up @@ -67,6 +70,11 @@ type inferProcedures<TObj extends ProcedureRecord> = {
*/
export type UseTRPCQueryResult<TData, TError> = UseQueryResult<TData, TError>;

/**
* @internal
*/
export type UseTRPCSuspenseQueryResult<TData, TError> = UseSuspenseQueryResult<TData, TError>;

/**
* @internal
*/
Expand Down Expand Up @@ -183,7 +191,27 @@ export function createHooksInternal<TRouter extends AnyRouter>(config: CreateTRP
...(opts as any),
},
queryClient,
) as UseTRPCQueryResult<TData, TError>;
) satisfies UseTRPCQueryResult<TData, TError>;
}

function useSuspenseQuery<
TPath extends keyof TQueryValues & string,
TQueryFnData = TQueryValues[TPath]['output'],
TData = TQueryValues[TPath]['output'],
>(
pathAndInput: [path: TPath, ...args: inferHandlerInput<TQueries[TPath]>],
opts?: UseTRPCSuspenseQueryOptions<TPath, TQueryValues[TPath]['input'], TQueryFnData, TData, TError>,
): UseTRPCSuspenseQueryResult<TData, TError> {
return __useSuspenseQuery(
{
queryKey: getArrayQueryKey(pathAndInput, 'query'),
queryFn: () => {
return (config.client as any).query(...getClientArgs(pathAndInput, opts));
},
...(opts as any),
},
queryClient,
) satisfies UseTRPCSuspenseQueryResult<TData, TError>;
}

function useMutation<TPath extends keyof TMutationValues & string, TContext = unknown>(
Expand Down Expand Up @@ -212,7 +240,12 @@ export function createHooksInternal<TRouter extends AnyRouter>(config: CreateTRP
},
},
queryClient,
) as UseTRPCMutationResult<TMutationValues[TPath]['output'], TError, TMutationValues[TPath]['input'], TContext>;
) satisfies UseTRPCMutationResult<
TMutationValues[TPath]['output'],
TError,
TMutationValues[TPath]['input'],
TContext
>;
}

/**
Expand Down Expand Up @@ -287,7 +320,7 @@ export function createHooksInternal<TRouter extends AnyRouter>(config: CreateTRP
...(opts as any),
},
queryClient,
) as UseTRPCInfiniteQueryResult<TQueryValues[TPath]['output'], TError>;
) satisfies UseTRPCInfiniteQueryResult<TQueryValues[TPath]['output'], TError>;
}

return {
Expand All @@ -301,6 +334,7 @@ export function createHooksInternal<TRouter extends AnyRouter>(config: CreateTRP
useMutation,
useSubscription,
useInfiniteQuery,
useSuspenseQuery,
};
}

Expand Down
13 changes: 13 additions & 0 deletions packages/trpc-react-query/src/createTRPCReact.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
type UseTRPCMutationResult,
type UseTRPCQueryResult,
type UseTRPCSubscriptionOptions,
type UseTRPCSuspenseQueryResult,
} from './createHooksInternal.tsx';
import { createSolidProxyDecoration } from './decorationProxy.ts';
import type {
Expand All @@ -36,6 +37,7 @@ import type {
UseTRPCInfiniteQueryOptions,
UseTRPCMutationOptions,
UseTRPCQueryOptions,
UseTRPCSuspenseQueryOptions,
} from './types.ts';

/**
Expand All @@ -58,6 +60,17 @@ export type DecorateProcedure<
>,
) => UseTRPCQueryResult<TData, TRPCClientErrorLike<TProcedure>>;

useSuspenseQuery: <TOutput = inferProcedureOutput<TProcedure>, TData = inferProcedureOutput<TProcedure>>(
input: inferProcedureInput<TProcedure>,
opts?: UseTRPCSuspenseQueryOptions<
TPath,
inferProcedureInput<TProcedure>,
TOutput,
TData,
TRPCClientErrorLike<TProcedure>
>,
) => UseTRPCSuspenseQueryResult<TData, TRPCClientErrorLike<TProcedure>>;

fetchQuery<TOutput = inferProcedureOutput<TProcedure>>(
input: inferProcedureInput<TProcedure>,
opts?: TRPCFetchQueryOptions<inferProcedureInput<TProcedure>, TRPCClientErrorLike<TProcedure>, TOutput>,
Expand Down
16 changes: 14 additions & 2 deletions packages/trpc-react-query/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ import type {
MutationOptions,
QueryClient,
QueryKey,
QueryObserverOptions,
UseInfiniteQueryOptions,
UseQueryOptions,
UseSuspenseQueryOptions,
} from '@tanstack/react-query';
import type { TRPCRequestOptions, TRPCUntypedClient } from '@trpc/client';
import type { AnyRouter, MaybePromise } from '@trpc/server';
Expand Down Expand Up @@ -57,7 +58,7 @@ export type CreateQueryOptions<
TError = unknown,
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
> = OmitUseless<QueryObserverOptions<TQueryFnData, TError, TData, TQueryKey>>;
> = OmitUseless<UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>>;

export type CreateInfiniteQueryOptions<
TQueryFnData = unknown,
Expand All @@ -66,6 +67,13 @@ export type CreateInfiniteQueryOptions<
TQueryKey extends QueryKey = QueryKey,
> = OmitUseless<UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryFnData, TQueryKey>>;

export type CreateSuspenseQueryOptions<
TQueryFnData = unknown,
TError = unknown,
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
> = OmitUseless<UseSuspenseQueryOptions<TQueryFnData, TError, TData, TQueryKey>>;

export type CreateMutationOptions<TInput, TError, TOutput, TContext = unknown> = OmitUseless<
MutationOptions<TInput, TError, TOutput, TContext>
>;
Expand All @@ -78,6 +86,10 @@ export interface UseTRPCInfiniteQueryOptions<TPath, TInput, TOutput, TError>
export interface UseTRPCQueryOptions<TPath, TInput, TOutput, TData, TError>
extends CreateQueryOptions<TOutput, TError, TData, [TPath, TInput]> {}

// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface UseTRPCSuspenseQueryOptions<TPath, TInput, TOutput, TData, TError>
extends CreateSuspenseQueryOptions<TOutput, TError, TData, [TPath, TInput]> {}

export interface UseTRPCMutationOptions<TInput, TError, TOutput, TContext = unknown>
extends CreateMutationOptions<TInput, TError, TOutput, TContext> {}

Expand Down

0 comments on commit da6fec0

Please sign in to comment.