useQuery returns data as undefined
const { data } = useQuery(...) logs undefinedShort answer
data is undefined until the query succeeds, so check isPending and isError first. If it stays undefined after loading, your queryFn probably returned nothing: a missing return, or a fetch error that was not thrown. A query function must return the data and may not resolve undefined.
Fix it fast
1Find out which cause you have
Log the status next to data. It says whether the query is still loading, failed, or succeeded with nothing.
const { data, status, error, fetchStatus } = useQuery({ queryKey: ['todos'], queryFn: fetchTodoList }); console.log({ data, status, fetchStatus, error });2Match what you see, then jump to its fix
- 1
status is 'pending' on the first renderThe query has not finished yetFix - 2
status is 'error' or the query is treated as failed; the network tab shows a good responseThe queryFn does not return the dataFix - 3
The server answered 4xx or 5xx but the query looks like success with the error body as datafetch got an HTTP error that was not thrownFix
- 1
What does the error look like?
const { data } = useQuery(...) logs undefinedTypeError: Cannot read properties of undefined (reading 'map')
Cause 1 of 3
The query has not finished yet
1Check
A query is in one of three states, pending, error or success. data is available in success only.
grep -rn "useQuery(" src/2Fix
Handle pending and error before reading data.
const { isPending, isError, data, error } = useQuery({ queryKey: ['todos'], queryFn: fetchTodoList });
if (isPending) return <span>Loading...</span>;
if (isError) return <span>Error: {error.message}</span>;
return <ul>{data.map(t => <li key={t.id}>{t.title}</li>)}</ul>;3Verify
The map call no longer runs while data is undefined.
npm run devConfirmed by tanstack.com
Cause 2 of 3
The queryFn does not return the data
1Check
A query function must return a promise that resolves the data. TanStack Query treats a resolved undefined as a failed query. A missing return, or braces in an arrow function without return, is the usual cause.
grep -rn "queryFn" -A 4 src/2Fix
Return the value, and return null if nothing is a valid result.
// wrong: no return
queryFn: async () => { await axios.get('/api/todos'); }
// right
queryFn: async () => {
const res = await axios.get('/api/todos');
return res.data;
}3Verify
status becomes 'success' and data holds the array.
npm run devConfirmed by tanstack.com
Cause 3 of 3
fetch got an HTTP error that was not thrown
1Check
axios throws on unsuccessful HTTP status; fetch does not. With fetch, a 404 resolves normally.
grep -rn "fetch(" src/2Fix
Check response.ok and throw, so the query goes to the error state.
async function fetchTodoList() {
const response = await fetch('/api/todos');
if (!response.ok) throw new Error('Failed to load todos');
return response.json();
}3Verify
A failing URL now shows isError instead of a silent empty list.
curl -i http://localhost:3000/api/todosConfirmed by tanstack.com
How do I stop it coming back?
- Always branch on isPending and isError before using data.
- Return from every queryFn path, and return null for an intentional empty result.
- Type the queryFn return so TypeScript catches a missing return.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- QistLockA NestJS and React SaaS driving an Android Device Owner agent that locks financed phones when payments lapse.
- TaskvareA task and project-management suite: React on the web, Flutter on mobile, TypeScript underneath.
Related fixes
Web apps
TanStack Query says the query function returned undefined
Query data cannot be undefined. Please make sure to return a value other than undefined from your query function
TanStack Query treats a query that resolves to undefined as failed.
2 causes, each with a fixWeb apps
invalidateQueries or refetch does nothing in React Query and React Native
data does not update after mutation
invalidateQueries only refetches queries whose key starts with the key you pass and that are in use.
4 causes, each with a fixWeb apps
TanStack Query throws 'No QueryClient set' on useQuery
Error: No QueryClient set, use QueryClientProvider to set one
useQuery reads the QueryClient from React context.
2 causes, each with a fixWeb apps
onSuccess and onError on useQuery do nothing after upgrading TanStack Query
onError callback not working after upgrading to React Query v5
TanStack Query v5 removed onSuccess, onError and onSettled from queries, so options passed to useQuery are ignored.
2 causes, each with a fixWeb apps
TanStack Query useInfiniteQuery reloads every page again and again
the network tab shows page 1, 2, 3 requested again one after another
An infinite query is one cached entry with many pages.
3 causes, each with a fixWeb apps
TypeScript cannot find the module @tanstack/react-query
Cannot find module '@tanstack/react-query' or its corresponding type declarations.
Either the package is not installed under this exact name, or the editor cannot see it.
2 causes, each with a fix