From 29b7c5c8d10d5315fea27fc25f1f153c6c12dfbf Mon Sep 17 00:00:00 2001
From: MohamedBassem <me@mbassem.com>
Date: Sat, 2 Mar 2024 20:45:11 +0000
Subject: fix: Fix hydration in list view caused by the spinner

---
 packages/web/lib/providers.tsx | 30 +++++++++++++++++++++++++++++-
 1 file changed, 29 insertions(+), 1 deletion(-)

(limited to 'packages/web/lib/providers.tsx')

diff --git a/packages/web/lib/providers.tsx b/packages/web/lib/providers.tsx
index 0c721c1e..5c4649b5 100644
--- a/packages/web/lib/providers.tsx
+++ b/packages/web/lib/providers.tsx
@@ -9,6 +9,34 @@ import superjson from "superjson";
 import { SessionProvider } from "next-auth/react";
 import { Session } from "next-auth";
 
+function makeQueryClient() {
+  return new QueryClient({
+    defaultOptions: {
+      queries: {
+        // With SSR, we usually want to set some default staleTime
+        // above 0 to avoid refetching immediately on the client
+        staleTime: 60 * 1000,
+      },
+    },
+  });
+}
+
+let browserQueryClient: QueryClient | undefined = undefined;
+
+function getQueryClient() {
+  if (typeof window === "undefined") {
+    // Server: always make a new query client
+    return makeQueryClient();
+  } else {
+    // Browser: make a new query client if we don't already have one
+    // This is very important so we don't re-make a new client if React
+    // supsends during the initial render. This may not be needed if we
+    // have a suspense boundary BELOW the creation of the query client
+    if (!browserQueryClient) browserQueryClient = makeQueryClient();
+    return browserQueryClient;
+  }
+}
+
 export default function Providers({
   children,
   session,
@@ -16,7 +44,7 @@ export default function Providers({
   children: React.ReactNode;
   session: Session | null;
 }) {
-  const [queryClient] = React.useState(() => new QueryClient());
+  const queryClient = getQueryClient();
 
   const [trpcClient] = useState(() =>
     api.createClient({
-- 
cgit v1.2.3-70-g09d2

