Skip to content

Commit

Permalink
fix: stable query client (t3-oss#1772)
Browse files Browse the repository at this point in the history
Co-authored-by: Julius Marminge <[email protected]>
  • Loading branch information
mladenovic-13 and juliusmarminge committed Feb 22, 2024
1 parent 17c2a5e commit c3c4710
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/sixty-rats-drop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"create-t3-app": patch
---

fix: use singleton pattern for client-side QueryClient to support `useSuspenseQuery` when there is no parent `<Suspense>`-element
14 changes: 13 additions & 1 deletion cli/template/extras/src/trpc/react.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,22 @@ import { useState } from "react";
import { type AppRouter } from "~/server/api/root";
import { getUrl, transformer } from "./shared";

const createQueryClient = () => new QueryClient();

let clientQueryClientSingleton: QueryClient | undefined = undefined;
const getQueryClient = () => {
if (typeof window === "undefined") {
// Server: always make a new query client
return createQueryClient();
}
// Browser: use singleton pattern to keep the same query client
return (clientQueryClientSingleton ??= createQueryClient());
};

export const api = createTRPCReact<AppRouter>();

export function TRPCReactProvider(props: { children: React.ReactNode }) {
const [queryClient] = useState(() => new QueryClient());
const queryClient = getQueryClient();

const [trpcClient] = useState(() =>
api.createClient({
Expand Down

0 comments on commit c3c4710

Please sign in to comment.