query icon indicating copy to clipboard operation
query copied to clipboard

Refetch is ignored if fired during initial fetching of a query

Open AlgirdasVZ opened this issue 2 years ago • 5 comments

Describe the bug

Hello!

I have recently discovered a certain behavior in react-query, which causes some edge cases in our application. This is related to the query refetching during the initial load of the query.

Inside our application, we currently use the refetch method from queries for refetching the data upon receiving certain events. It usually works perfectly well - refetch cancels any running requests if there are any (because of the default cancelRefetch = true), and makes sure that we always receive newest data. However, it seems there is an exception - looks like refetch is ignored if it's called during the initial query fetch.

After looking into react-query source code, I noticed this part:

  fetch(
    options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
    fetchOptions?: FetchOptions,
  ): Promise<TData> {
    if (this.state.fetchStatus !== 'idle') {
      if (this.state.dataUpdatedAt && fetchOptions?.cancelRefetch) {
        // Silently cancel current fetch if the user wants to cancel refetches
        this.cancel({ silent: true })

which to me indicates that fetch is only being canceled if dataUpdatedAt is not a falsy value, and dataUpdatedAt becomes truthy one of two ways: when initial fetch succeeds, or if initialData is provided inside the query.

Is there maybe any other way to force refetching even though query is still initially loading? I assume such behavior could randomly cause issues in architectures where refetch is used as a reaction to events, even though I couldn't found similar reported issues inside tanstack-query repo.

Your minimal, reproducible example

https://codesandbox.io/p/sandbox/react-query-refetching-during-initial-fetch-kg6knf

Steps to reproduce

In our app we encounter issues with the following scenario:

  1. User opens a page where query is mounted for the first time, and starts the initial fetch.
  2. During the initial fetch we receive a websocket event from backend, informing us that the data got updated and needs to be refetched, so we call the "refetch" method of the query from step 1
  3. Refetch is ignored because the query is still fetching initially
  4. The initial fetch of the query from step 1 completes, containing old incorrect data

In the codesandbox I added two components side to side to demonstrate the issue - both examples contains identical code, except that in one of them the query has initialData defined.

  1. Upon enabling the query which does not have initialData, it can be seen that refetch is ignored, and the difference between start and end is the original 2s
  2. Upon enabling the query which has initialData, it can be seen that refetch is not ignored, and the difference between start and end is 3s, because refetch triggers fetching again after 1s

Expected behavior

As a dev i would expect to have a way to refetch the query even if such need arises during the initial fetch of the query.

How often does this bug happen?

None

Screenshots or Videos

No response

Platform

  • Browser: chrome

Tanstack Query adapter

None

TanStack Query version

v5.13.4

TypeScript version

No response

Additional context

No response

AlgirdasVZ avatar Dec 13 '23 16:12 AlgirdasVZ

I think you're right, that's why the flag is called cancelRefetch and not cancelFetch - it can only cancel a refetch, and a refetch is a fetch where we already have data.

Not sure why we have that implementation / limitation. I would argue that cancelFetch is more appropriate - why would we only do this for refetches. But not sure if we can fix this in a non-breaking way? If we change the implementation and remove the this.state.dataUpdatedAt check - it would change the behaviour and the cancelRefetch name would be confusing.

I tried that, but we do have a test that covers this scenario:

https://github.com/TanStack/query/blob/1f0088e5fa9030cbabc7a881c3e6b9cc127f70d9/packages/react-query/src/tests/useQuery.test.tsx#L514-L546

So, I really don't think we can change this right now. next major maybe? I always prefer less code and less surprising behaviour, but I also don't want to change this now without renaming the flag.


For your cases - what you can do is call queryClient.cancelQueries({ queryKey }) to manually cancel it instead of letting refetch take care of it. That should work.

TkDodo avatar Dec 16 '23 12:12 TkDodo

Hi @TkDodo, thanks for your answer!

I agree that the current flag name (cancelRefetch) works exactly as the name implies - it only cancels refetches. cancelFetch would make more sense, since the current behavior of cancelRefetch creates that blind spot, which might not be obvious for library users. Both flags could potentially coexist, but it would only make dx more confusing IMO, so I also agree with you that it would only make sense introducing it as a breaking change somewhere down the road (if such decision would be made).

P.S queryClient.cancelQueries was what I tried initially - this does not seem to cancel the initial fetch either, only the following ones. This also matches with the cancelQueries description, where canceling refetches is mentioned as a use case:

This is most useful when performing optimistic updates since you will likely need to cancel any outgoing query refetches so they don't clobber your optimistic update when they resolve.

AlgirdasVZ avatar Dec 20 '23 14:12 AlgirdasVZ

this does not seem to cancel the initial fetch either

Hmm I looked at the code and queryClient.cancelQueries should also cancel initial fetches.

I wrote a quick test for that to confirm, and it passes:

test('should also cancel initial queries', async () => {
  const key = queryKey()
  void queryClient.fetchQuery({
    queryKey: key,
    queryFn: async () => {
      await sleep(10)
      return 'data'
    },
  })
  await queryClient.cancelQueries({ queryKey: key })

  const state = queryClient.getQueryState(key)

  expect(state).toMatchObject({
    data: undefined,
    status: 'pending',
  })
})

TkDodo avatar Dec 20 '23 15:12 TkDodo

Aaah, apologies, seems to be my mistake, related with how query client was being imported. Query canceling seems to be working just as described. Thanks for your help! I believe this issue can be closed

AlgirdasVZ avatar Dec 20 '23 16:12 AlgirdasVZ

@AlgirdasVZ @TkDodo Thank you. This issue allowed me to half solve a use case in our product.

Just mentioning my use case if it will help someone else.

  1. Form including simple inputs
  2. using useQuery with refetch as manual submit activation for the form. The query is without side affect - just calculation returned from the server.
  3. Each change in the form (dirty state) activate reset of the query state. client.resetQueries(([...])

3 made the dataUpdatedAt 0 so the requests were not canceled if the user clicked on the submit couple of times.

I am not sure if this scenario is best practice use for react-query, but regardless, the mention to use initialData to effect dataUpdatedAt gave a somewhat solution for this case.

elpddev avatar Jan 15 '24 08:01 elpddev