Skip to content
Source
Sign inSign up
TanStack/query

Infinate querying when query fails and using suspense + enabled flag #2434

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

Describe the bug Using suspense + enabled flag to delay querying, when a query fails will cause infinite querying.

To Reproduce

Core code:

function query() {
  return new Promise((resolve, reject) => {
    console.count("query");
    setTimeout(() => reject("Query Error"), 1000);
  });
}

function DataFetch() {
  const [enabled, setEnabledStatus] = useState(false);
  useQuery("mock", query, { suspense: true, enabled, retry: 0 });

  return <button onClick={() => setEnabledStatus(true)}>Start</button>;
}

Complete code: https://codesandbox.io/s/react-query-bug-suspense-enabled-flag-2w762?file=/src/App.tsx

Steps to reproduce the behavior:

  1. Click the Start Button
  2. Look at Console, you will see many queries.

Expected behavior Throw Error and only query once.

Screenshots image

Desktop (please complete the following information):

  • OS: macOS
  • Browser: chrome
  • Version: 91.0.4472.114

Additional context After removing the enabled or suspense flag, anything works well.

  1. vimcaw(GitHub profile, opens in a new tab) changed the title

  2. We've also ran into this with Blitz.

    Here's a failing test to add to suspense.test.tsx:

      it('should not have infinite loop with error query when enabled goes from false to true', async () => {
        const key = queryKey()
    
        const consoleMock = mockConsoleError()
    
        let queryExecutions = 0
    
        function Page() {
          const [count, setCount] = React.useState(0)
          useQuery(
            key,
            async () => {
              console.log('Running query...')
              queryExecutions++
              await sleep(10)
              throw new Error('Suspense Error')
            },
            {
              enabled: count > 0,
              retry: false,
              suspense: true,
            }
          )
          return (
            <div>
              rendered
              <button onClick={() => setCount(c => c + 1)}>increment</button>
            </div>
          )
        }
    
        function App() {
          const { reset } = useQueryErrorResetBoundary()
          return (
            <ErrorBoundary
              onReset={reset}
              fallbackRender={() => <div>error boundary</div>}
            >
              <React.Suspense fallback="Loading...">
                <Page />
              </React.Suspense>
            </ErrorBoundary>
          )
        }
    
        const rendered = renderWithClient(queryClient, <App />)
    
        await waitFor(() => rendered.getByText('rendered'))
        fireEvent.click(rendered.getByText('increment'))
        await waitFor(() => rendered.getByText('Loading...'))
        await waitFor(() => rendered.getByText('rendered'))
        await sleep(100)
        expect(queryExecutions).toBe(1)
    
        consoleMock.mockRestore()
      })
  3. We ran into this as well when we removed a query from the cache inside the devtools. The query is permanently stuck in an infinite loop unless we remove the suspense flag, even if we restart the dev server or clear browser cache

  4. We're also running into the same problem even without enabled flag set to false initially. Setting suspense: true for the useQuery hook causes the infinite retry loop if the fetch function fails.

    Noticed this after upgrading from 3.5.12 to 3.18.1

  5. This error occurs since version 3.9.0

  6. 3.9.0 had a rather big re-write to keep side-effects out of the render function: https://github.com/tannerlinsley/react-query/pull/1775

  7. TkDodo added labelssuspense

  8. TkDodocommented

    @flybayer yep, the test is failing. I just wanted to ask if the assertions are really expected:

        await waitFor(() => rendered.getByText('rendered'))
        fireEvent.click(rendered.getByText('increment'))
        await waitFor(() => rendered.getByText('Loading...'))
        await waitFor(() => rendered.getByText('rendered'))

    after clicking the increment button, going to loading seems correct, but shouldn't we then see the fallback from the errorBoundary because the query fails?

    changing the last line to:

    -    await waitFor(() => rendered.getByText('rendered'))
    +    await waitFor(() => rendered.getByText('error boundary'))

    results in the error that this cannot be found at all, so it seems to be a problem that the error boundary is not shown at all 🤔 ?

  9. TkDodo added labelsbug

  10. @TkDodo ah yes, it should render the error boundary

  11. TkDodocommented

    @TkDodo ah yes, it should render the error boundary

    okay, it doesn't do that either :/ I tried to debug this a bit but to no success. Works fine without the enabled transition, really a bit strange. I couldn't pinpoint where the infinite re-renders were coming from. Maybe @boschni could help us here 🥺

  12. Any update on this ? I would be happy to work on it

  13. @mh-alahdadian yes please go ahead if you want :)

  14. I have found that logic of shouldFetchOptionally is wrong

    (!options.suspense ||
          query.state.status !== 'error' ||
          prevOptions.enabled === false)

    As you can see this condition should be false when suspense is true but we let it to fetch query again even though we know that it has error

    @TkDodo

  15. TkDodocommented

    we already have extended the condition quite some times to appease the suspense 😅 :

    https://github.com/tannerlinsley/react-query/blob/b84681fdc7d37645cd149f40e98cb18fd8bc393c/src/core/queryObserver.ts#L767-L781

    maybe you can show how you think the condition should look like in your opinion?

    FYI, we added the check in this PR:

    to fix this issue with suspense:

    this also caused a regression for non-suspense usage:

    which we then fixed by making the condition solely for suspense:

    just want to point out that if we touch that again, we have to make sure to only influence suspense usage and not everything else please, because regressions for non-suspense users are not worth it (suspense is still experimental)

  16. What if we remove prevOptions.enabled === false from the condition? I think that is not needed because we know that state is 'error' . I removed that one and it fixes this bug and all tests are passed as well. is it enough ?

  17. sure, I think we added a test case for the other situation as well so that we don't break it again. please add the test from this issue as well so that we can see that it passes.

    also tagging @JaeYeopHan - maybe he remembers why this condition was added?

  18. maybe... this point: https://github.com/tannerlinsley/react-query/pull/2556

    but... at that time, condition for preventing infinite query was prevQuery.state.status !== 'error'. and now it is not(options.suspense), so I think it would be ok to remove the enabled === false option! :)

  19. but... at that time, condition for preventing infinite query was prevQuery.state.status !== 'error'.

    and now it is not(options.suspense), so I think it would be ok to remove the enabled === false option! :)

    yeah, could be. I would trust the tests here. If the new test works and the old test still works, too, I'm happy to merge this :)

  20. @mh-alahdadian are you planning to contribute?

  21. TkDodo closed this

  22. :tada: This issue has been resolved in version 3.34.3 :tada:

    The release is available on:

    Your semantic-release bot :package::rocket:

  23. tannerlinsley added labelsreleased

  24. Popping in to say thank you guys so much for resolving this! The fix came just as we had identified this as a prod issue and really saved me a ton of grief : )

  25. :tada: This issue has been resolved in version 4.0.0-alpha.4 :tada:

    The release is available on:

    Your semantic-release bot :package::rocket:

  26. tannerlinsley added labelsreleased on @alpha

  27. 🎉 This issue has been resolved in version 3.34.3 🎉

    The release is available on:

    Your semantic-release bot 📦🚀

    @flybayer could you please fix the problem in blitz ? thank you very much.

Sign in to join this conversation.