Skip to content

Commit 4201a1d

Browse files
committed
refactor: extract QueryClient to a singleton module
Move the QueryClient out of createAppRouter() into its own module so the same instance is shared across the app and any code that imports it (e.g. TWD tests can call queryClient.clear() between runs to avoid cache leaking across spa-style twd.visit navigations).
1 parent 0ef9f2c commit 4201a1d

3 files changed

Lines changed: 12 additions & 12 deletions

File tree

src/main.tsx

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
import ReactDOM from 'react-dom/client'
22
import { RouterProvider } from '@tanstack/react-router'
33
import { QueryClientProvider } from '@tanstack/react-query'
4+
import { queryClient } from './query-client'
45
import { createAppRouter } from './router'
56

6-
const { router, queryClient } = createAppRouter()
7+
const router = createAppRouter()
78

89
const rootElement = document.getElementById('app')!
910

src/query-client.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import { QueryClient } from '@tanstack/react-query'
2+
3+
export const queryClient = new QueryClient({
4+
defaultOptions: {
5+
queries: { staleTime: 1000 * 30 },
6+
},
7+
})

src/router.tsx

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,19 @@
11
import { createRouter } from '@tanstack/react-router'
2-
import { QueryClient } from '@tanstack/react-query'
2+
import { queryClient } from './query-client'
33
import { routeTree } from './routeTree.gen'
44

55
export function createAppRouter() {
6-
const queryClient = new QueryClient({
7-
defaultOptions: {
8-
queries: { staleTime: 1000 * 30 },
9-
},
10-
})
11-
12-
const router = createRouter({
6+
return createRouter({
137
routeTree,
148
scrollRestoration: true,
159
defaultPreload: 'intent',
1610
defaultPreloadStaleTime: 0,
1711
context: { queryClient },
1812
})
19-
20-
return { router, queryClient }
2113
}
2214

2315
declare module '@tanstack/react-router' {
2416
interface Register {
25-
router: ReturnType<typeof createAppRouter>['router']
17+
router: ReturnType<typeof createAppRouter>
2618
}
2719
}

0 commit comments

Comments
 (0)