Skip to content

Commit

Permalink
fix: fix infinite requests for useSuspenseQuery (#157)
Browse files Browse the repository at this point in the history
  • Loading branch information
Ploffi authored Dec 4, 2024
1 parent 85a61ca commit 56e646e
Showing 1 changed file with 20 additions and 2 deletions.
22 changes: 20 additions & 2 deletions packages/vike-react-query/integration/Wrapper.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export { Wrapper }

import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { QueryClient, QueryClientProvider, type QueryClientConfig } from '@tanstack/react-query'
import React, { ReactNode, useState } from 'react'
import { StreamedHydration } from './StreamedHydration.js'
import { usePageContext } from 'vike-react/usePageContext'
Expand All @@ -10,7 +10,7 @@ function Wrapper({ children }: { children: ReactNode }) {
const { queryClientConfig, FallbackErrorBoundary = PassThrough } = pageContext.config
const [queryClient] = useState(() => {
const config = typeof queryClientConfig === 'function' ? queryClientConfig(pageContext) : queryClientConfig
return new QueryClient(config)
return getQueryClient(config)
})

return (
Expand All @@ -25,3 +25,21 @@ function Wrapper({ children }: { children: ReactNode }) {
function PassThrough({ children }: any) {
return <>{children}</>
}

let clientQueryClient: QueryClient | undefined
function getQueryClient(config: QueryClientConfig | undefined) {
if (!isBrowser()) return new QueryClient(config)
// React may throw away a partially rendered tree if it suspends, and then start again from scratch.
// If it's no suspense boundary between the creation of queryClient and useSuspenseQuery,
// then the entire tree is thrown away, including the creation of queryClient, which may produce infinity refetchs
// https://github.com/TanStack/query/issues/6116#issuecomment-1904051005
// https://github.com/vikejs/vike-react/pull/157
if (!clientQueryClient) clientQueryClient = new QueryClient(config)
return clientQueryClient
}

function isBrowser() {
// Using `typeof window !== 'undefined'` alone is not enough because some users use https://www.npmjs.com/package/ssr-window
return typeof window !== 'undefined' && typeof window.scrollY === 'number'
// Alternatively, test whether environment is a *real* browser: https://github.com/brillout/picocolors/blob/d59a33a0fd52a8a33e4158884069192a89ce0113/picocolors.js#L87-L89
}

0 comments on commit 56e646e

Please sign in to comment.