Skip to content

useSuspenseQuery types: data can be undefined #8591

@OliverJAsh

Description

@OliverJAsh

Describe the bug

useSuspenseQuery can return undefined data e.g. if select throws, however the types do not reflect this.

Your minimal, reproducible example

https://stackblitz.com/edit/tanstack-query-2bfa3dy1?file=src%2Findex.tsx&preset=node

Steps to reproduce

const query = queryOptions({
  queryKey: ['foo'],
  queryFn: () => {
    const data = { a: { b: 'c' } };
    return Promise.resolve(data);
  },
  select: (x) => {
    throw new Error('foo');
    return x.a;
  },
});

function A() {
  const queryClient = useQueryClient();
  const { data, error } = useSuspenseQuery(query);
  console.log('Query result', { data, error });
  // ❌ `data` is `undefined` at runtime, but
  // types make it look like it will always exist
  return data.b;
}

Expected behavior

The types should match the runtime behaviour.

I also wonder whether in this case the error should be thrown?

From the docs:

Not all errors are thrown to the nearest Error Boundary per default - we're only throwing errors if there is no other data to show.

In this case, we don't have data to show, because select always fails.

How often does this bug happen?

None

Screenshots or Videos

No response

Platform

N/A

Tanstack Query adapter

None

TanStack Query version

5.63.0

TypeScript version

No response

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions