Skip to content
Source
Sign inSign up
TanStack/query

Suspended query continues to suspend until queryFn promise is fullfiled even when the query data is updated #10924

Send to my agent
ClosedMrBr(GitHub profile, opens in a new tab) opened this issue 5 comments

Describe the bug

Suspense query keeps suspending when data exists. Originally, I noticed the problem in streamedQuery in combination with useSuspenseQuery. The issue reflects in such way that suspense query keeps suspending even after the first stream chunk is received.

I'd like to note that the aforementioned behaviour could be useful in some cases, but that's a separate issue I guess.

Your minimal, reproducible example

https://codesandbox.io/p/sandbox/cranky-benz-xvt2n2

Steps to reproduce

  1. Go to https://codesandbox.io/p/sandbox/cranky-benz-xvt2n2?file=%2Fsrc%2FApp.js
  2. Click the button
  3. Loading text remains even though the query client has the data for the key

Expected behavior

I'd expect data to show.

How often does this bug happen?

Every time

Screenshots or Videos

No response

Platform

  • Every platform

Tanstack Query adapter

None

TanStack Query version

5.101.0

TypeScript version

No response

Additional context

An idea about solution. Maybe wrapping suspense queryFn result with additional promise could provide more control?

Not sure what is the right way to handle the ongoing promise when the data is set programatically? Should this behaviour be controlled by user through options?

  1. @MrBr There is a way to manually update the cache with a button. You can keep using useSuspenseQuery, but first cancel the fetch promise to release Suspense.

    <button
      onClick={async () => {
        await queryClient.cancelQueries({ queryKey })
        queryClient.setQueryData(queryKey, "MANUAL OK")
      }}
    >
      Set query state
    </button>
  2. @nijuse I've demonstrated the root cause of the issue but the actual issue occurs in streamedQuery. Since useSuspenseQuery will continue to suspend until streamed query Async generator is "done" it makes it unusable with suspense. In most cases (I'd say), you want to show whatever you have in the cache instead of suspending.

    cc @TkDodo, we talked about this in Amsterdam on React Summit. Do you have an idea how to tackle this?

  3. TkDodo added labelsbug

  4. TkDodo added labelssuspense

  5. TkDodo added labelspackage: react-query

  6. @MrBr can you maybe try out the preview build if that fixes your real issue with streaming too?

    npm i https://pkg.pr.new/@tanstack/react-query@10994
  7. @TkDodo I tested it and it seems something isn't working right. Few things I've noted:

    1. Abort signal get's aborted on the first update, if the stream is properly integrated with query, this will close the stream
    2. When ignoring the abort signal, it seems to be working, but it's not consistent. Not sure if it's something related to my environment, but sometimes it just stops working. This reflects in the second update not being registered by query. There must be some kind of race condition.

    I couldn't make the example work in Codesandbox. It behaves like there's no changes. https://codesandbox.io/p/sandbox/quiet-pond-6sv7wm

    Sharing the example I've used locally.

    'use client';
    
    import {
      QueryClientProvider,
      QueryClient,
      useSuspenseQuery,
      experimental_streamedQuery,
    } from '@tanstack/react-query';
    import { Suspense } from 'react';
    
    const queryClient = new QueryClient({
      defaultOptions: {
        queries: {
          experimental_prefetchInRender: true,
        },
      },
    });
    const queryKey = ['state'];
    
    export async function* numberStreamGenerator(signal: AbortSignal): AsyncGenerator<number> {
      let count = 0;
    
      while (true) {
        await new Promise((resolve, reject) => {
          const timer = setTimeout(resolve, 1000);
    
          // signal.addEventListener('abort', (e) => {
          //   console.log('aborted', e);
          //   clearTimeout(timer);
          //   reject(new DOMException('Aborted', 'AbortError'));
          // });
        });
        console.log(count);
    
        if (signal.aborted || count > 3) break;
    
        count += 1;
        yield count;
      }
    }
    
    const QueryStateUpdateExample = () => {
      const { data } = useSuspenseQuery({
        queryKey,
        queryFn: experimental_streamedQuery({
          streamFn: ({ signal }) => numberStreamGenerator(signal),
          reducer: (_, chunk: number) => {
            return chunk;
          },
        }),
      });
    
      return (
        <div className="App">
          <h2>{data}</h2>
        </div>
      );
    };
    
    export default function App() {
      return (
        <QueryClientProvider client={queryClient}>
          <h2>
            Suspended query continues to suspend until queryFn promise is fullfiled even when the query
            data is updated.
          </h2>
    
          <Suspense fallback={<p>Loading ...</p>}>
            <QueryStateUpdateExample />
          </Suspense>
        </QueryClientProvider>
      );
    }
    
  8. TkDodo closed this

Sign in to join this conversation.