Replies: 2 comments
|
Sorry it was another my fault... |
|
The key thing is that A render can still reach your
In v5, if (query.isPending) return <Spinner />
if (query.isError) return <ErrorUI />
if (!query.data) return nullAnd anything like If you need the server build to wait for the query, that usually means prefetching / hydration or using suspense-oriented flow instead of relying on |
|
The mechanism comes down to how v5 derives During a Next.js server render (SSG/SSR) the query is created but never actually fetches: without So Block A is skipped because Your three questions directly:
Fix the guard by branching on const { data, isPending, isError } = useQuery({ /* ... */ })
if (isPending) {
return <DefaultLayout><Spinner size={40} /></DefaultLayout>
}
if (isError || !data) {
// ...
}Because Mental model for v5:
Refs: https://tanstack.com/query/latest/docs/framework/react/guides/queries and https://tanstack.com/query/latest/docs/framework/react/guides/ssr |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Context:
I'm using Next.js (SSG) with TanStack Query. I have a standard conditional rendering pattern based on the query state. During the build process, I'm encountering a
Prerender Errorbecause the code enters a block containing browser-only APIs (alert,router.push).Code Snippet:
The Issue:
During the Next.js build process (SSG), I expected the renderer to stop at Block A because
isLoadingshould betrueby default when no initial data or hydration is provided.However, it seems the renderer bypasses Block A and executes Block B, hitting the
alert()androuter.push()which are not defined on the server, leading to a build failure.My Questions (Focusing on Internal Mechanism):
I am aware that moving side effects into
useEffector usingtypeof window !== 'undefined'checks would "fix" the error. However, I want to understand the underlying mechanism:isLoadingcondition and enter the!data || isErrorblock during the server-side build? DoesuseQueryimmediately transition to a non-loading state (likestatus: 'error'or just empty data) on the server if noprefetchQueryis used?isLoadingistrueduring the first render on the server? Or does the absence of afetchenvironment cause it to resolve to "no data" instantly?loadingstatus when it detects a non-browser environment?I'd love to understand why this happens internally to write more robust SSR/SSG-friendly code. Thanks!
Note to Maintainers:
I suspect this behavior might be closely tied to Next.js's specific pre-rendering engine, but I'm reaching out here to understand the internal state management of TanStack Query in non-browser environments. If this is strictly a Next.js-side behavior, I apologize for the noise, but any insight into how
useQueryinitializes its state on the server would be immensely helpful!Thank you for your time and for maintaining such a great library.
All reactions