TanStack QueryReact QueryError Fix2026 Updated

TanStack Query: data Is Undefined— queryFn & Setup Fix [2026]

Also covers: QueryClientProvider · queryFn return · enabled flag · TypeScript generics · initialData · placeholderData

January 20267 min readTanStack Query v5 · React · TypeScript

⚡ The Problem

Error
const { data } = useQuery({ queryKey: ["posts"], queryFn: fetchPosts })
console.log(data)  // undefined — even after loading finishes

✅ Check these in order

Diagnostic checklist
1. Is QueryClientProvider wrapping your component tree?
2. Does queryFn return the data? (return await res.json())
3. Is enabled not set to false?
4. Check isLoading — data is always undefined while loading

Why TanStack Query Data Is Undefined

TanStack Query data is undefined in three distinct situations: while the query is loading (normal), when the query is disabled (enabled: false), or when queryFn doesn't return the data. The first is expected — handle it with a loading state. The latter two are bugs.

1

Wrap App in QueryClientProvider

Missing provider — useQuery throws or returns undefined
3 min
providers/query-client-provider.tsx
"use client"

import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { ReactQueryDevtools } from "@tanstack/react-query-devtools"
import { useState } from "react"

export function Providers({ children }: { children: React.ReactNode }) {
  // ✅ Create QueryClient inside component — not at module level
  // This ensures each user session gets its own cache (important for SSR)
  const [queryClient] = useState(
    () => new QueryClient({
      defaultOptions: {
        queries: {
          staleTime: 60 * 1000,   // 1 minute
          retry: 1,
        },
      },
    })
  )

  return (
    <QueryClientProvider client={queryClient}>
      {children}
      <ReactQueryDevtools initialIsOpen={false} />
    </QueryClientProvider>
  )
}
app/layout.tsx — wrap entire app
import { Providers } from "@/providers/query-client-provider"

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <Providers>           {/* ← wraps everything */}
          {children}
        </Providers>
      </body>
    </html>
  )
}
2

Return Data from queryFn

Most common bug — missing return statement
2 min
queryFn must return data
// ❌ Returns undefined — missing return
const { data } = useQuery({
  queryKey: ["posts"],
  queryFn: async () => {
    const res = await fetch("/api/posts")
    await res.json()   // ← parsed but not returned!
  }
})

// ✅ Fix — return the parsed data
const { data } = useQuery({
  queryKey: ["posts"],
  queryFn: async () => {
    const res = await fetch("/api/posts")
    if (!res.ok) throw new Error("Failed to fetch posts")
    return res.json()   // ← return the data
  }
})

// ✅ Better — reusable fetch function
async function fetchPosts(): Promise<Post[]> {
  const res = await fetch("/api/posts")
  if (!res.ok) throw new Error(`HTTP ${res.status}`)
  return res.json()
}

const { data, isLoading, error } = useQuery({
  queryKey: ["posts"],
  queryFn: fetchPosts,
})
3

Fix enabled: false Blocking the Query

Query never runs — data permanently undefined
2 min
enabled — conditional query execution
// ❌ Wrong — disabled query never runs, data stays undefined
const { data } = useQuery({
  queryKey: ["user"],
  queryFn: fetchUser,
  enabled: false,   // ← intentionally disabled — maybe forgot to remove?
})

// ✅ Conditionally enable — runs only when userId exists
const { userId } = useAuth()
const { data: user } = useQuery({
  queryKey: ["user", userId],
  queryFn: () => fetchUser(userId!),
  enabled: !!userId,   // ← runs as soon as userId is available
})

// ✅ Dependent query — runs after first query resolves
const { data: user } = useQuery({ queryKey: ["user"], queryFn: fetchUser })
const { data: posts } = useQuery({
  queryKey: ["posts", user?.id],
  queryFn: () => fetchPostsByUser(user!.id),
  enabled: !!user?.id,   // ← waits for user query to complete
})
4

Add TypeScript Generics to useQuery

data typed as unknown or any
2 min
Type-safe useQuery with generics
import { useQuery } from "@tanstack/react-query"

interface Post {
  id: string
  title: string
  content: string
  createdAt: string
}

// TanStack Query v5 — generics: <TData, TError>
const { data, isLoading, error } = useQuery<Post[], Error>({
  queryKey: ["posts"],
  queryFn: async (): Promise<Post[]> => {
    const res = await fetch("/api/posts")
    if (!res.ok) throw new Error("Failed to fetch")
    return res.json()
  },
})

// data is now typed as Post[] | undefined
if (isLoading) return <Skeleton />
if (error) return <ErrorMessage error={error.message} />
if (!data) return null

// data is Post[] here — TypeScript knows
return <PostList posts={data} />
5

Use initialData or placeholderData

Show content immediately before query resolves
3 min
initialData and placeholderData patterns
// placeholderData — shown during loading, not cached
const { data } = useQuery({
  queryKey: ["posts"],
  queryFn: fetchPosts,
  placeholderData: [],   // shows empty array during loading
})

// placeholderData from previous query (pagination)
import { keepPreviousData } from "@tanstack/react-query"
const { data, isPlaceholderData } = useQuery({
  queryKey: ["posts", page],
  queryFn: () => fetchPosts(page),
  placeholderData: keepPreviousData,  // keeps previous page while next loads
})

// initialData — seeds the cache (treated as real data)
const { data } = useQuery({
  queryKey: ["posts"],
  queryFn: fetchPosts,
  initialData: serverSidePosts,   // from getServerSideProps or Server Component
  initialDataUpdatedAt: Date.now() - 60000,  // mark as 60s old — triggers refetch
})

Use placeholderData for skeleton UX — it shows placeholder content during loading but always refetches. Use initialData when you have real data from SSR — it's treated as cached data and only refetches when stale.

Prevention

Frequently Asked Questions

Why is TanStack Query data undefined on first render?+
data is always undefined on the first render while the query is loading. This is normal and expected — use isLoading or isPending to show a skeleton, and only render data-dependent UI after the query resolves. If data stays undefined after loading, check that queryFn returns a value.
Why does my queryFn cause data to be undefined?+
If your queryFn doesn't explicitly return the fetched data, it returns undefined by default. Ensure your async function returns the parsed response: return await res.json() — not just await res.json() without the return statement.
What does enabled: false do in TanStack Query?+
enabled: false prevents the query from running automatically. The query stays in 'idle' state and data is undefined. Use enabled to conditionally run queries — for example, only fetch user data after authentication: enabled: !!userId.
How do I show data immediately while TanStack Query fetches?+
Use placeholderData to show temporary data while the real data loads. placeholderData doesn't get cached — it only appears during the loading state. Alternatively, use initialData to seed the cache with pre-fetched or server-side data.
Can I use TanStack Query with Next.js App Router?+
Yes. Create a QueryClient in a Client Component provider and wrap your app. Use @tanstack/react-query with ReactQueryStreamedHydration or dehydrate/hydrate for server-side data prefetching. The query client must be created per-request on the server, not as a singleton.
Why does TypeScript show 'data is possibly undefined' with TanStack Query?+
TanStack Query v5 types data as T | undefined by default because data is undefined during loading. Either add a loading guard before accessing data, or use the select option to transform the data. You can also use the select option to provide a default value when data is undefined.

Need Expert Help?

We Build React Apps with TanStack Query

Softplix engineers implement TanStack Query for data fetching, caching, and real-time sync in React and Next.js applications. Let us help.

Talk to an Engineer