Skip to content

useQueries with keepPreviousData:true can get to infinite fetch loop when toggling a query off and on #2680

@jvuoti

Description

@jvuoti

When using useQueries to issue optional queries, you can seemingly get to an infinite fetch loop if you toggle the same query off and on again. This seems to only happen when having the keepExistingData: true set, as well as only when you toggle some other query than the last one.

We noticed this in one of our views which uses useQueries to fetch one or two data series, depending on what the user chooses. If the user toggles one data series off and then on again, the view will start to refetch all the data over and over again.

To Reproduce
Steps to reproduce the behavior:

  1. Go to https://codesandbox.io/s/nice-sid-9tkgi?file=/src/index.js -> the view should load two queries
  2. Click on 'Fetch with ID 1' to toggle the query off -> only query with ID 2 is fetched and result is shown
  3. Click on 'Fetch with ID 1' again to toggle the query -> both queries are fetched and result shown
  4. However, checking the dev tools you can see both the queries stay in "fetching" state. Also the console shows the queries are being issued over and over again:

image

Expected behavior
If you toggle the first query back on, the data should be fetched again only once.

Additional info

react-query version 3.23.2

It seems that if you toggle only the last query off and on, this does not happen. e.g. in the codesandbox, toggle "Fetch with ID 2" off and on again, and no additional fetches are issued.

Also, this only seems to happen if you have the keepExistingData:true set for the queries. We have now turned that off for our queries, and the view no longer issues extra queries.

Desktop:

  • OS: MacOS Big Sur 11.6
  • Browser: Chrome 93.0.4577.63, Firefox 91.0.2

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingreleased

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions