Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Next.js and React

useQuery returns data as undefined

Errorconst { data } = useQuery(...) logs undefined

Short 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.

  • Applies to TanStack Query v5, React 19
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 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 });
  2. 2Match what you see, then jump to its fix

    1. 1status is 'pending' on the first renderThe query has not finished yetFix
    2. 2status is 'error' or the query is treated as failed; the network tab shows a good responseThe queryFn does not return the dataFix
    3. 3The 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

What does the error look like?

  • const { data } = useQuery(...) logs undefined
  • TypeError: 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 dev

Confirmed by tanstack.com

Did this fix it?

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 dev

Confirmed by tanstack.com

Did this fix it?

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/todos

Confirmed by tanstack.com

Did this fix it?

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:

Related fixes

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.