query icon indicating copy to clipboard operation
query copied to clipboard

#initialState set incorrectly to persisted state

Open rklomp opened this issue 1 year ago • 3 comments

Describe the bug

When using PersistQueryClientProvider the query #initialState will be set to the state loaded from storage on page/app load. Running resetQueries will now give unexpected behaviour across app reloads.


Looks like hydrate is using QueryCache.build() to create queries https://github.com/TanStack/query/blob/main/packages/query-core/src/hydration.ts#L145-L159 This will create a new Query: https://github.com/TanStack/query/blob/main/packages/query-core/src/queryCache.ts#L111-L118 Since state is set, #initialState will be set to config.state https://github.com/TanStack/query/blob/main/packages/query-core/src/query.ts#L177

Your minimal, reproducible example

https://codesandbox.io/p/sandbox/query-async-test-rqf58n

Steps to reproduce

  1. Open Sandbox. And press Refetch Query A. If this is the first time you open the page you should see in the console:
Render MySubComponent pending fetching
Render MySubComponent success idle
  1. Reload page and press Refetch Query A again. Data was now loaded from storage and you will see
Render MySubComponent success fetching
Render MySubComponent success idle
  1. Remove the REACT_QUERY_OFFLINE_CACHE and refresh, it is working as expected
Render MySubComponent pending fetching
Render MySubComponent success idle
  1. Go to Step 2

Expected behavior

I expect initialState to be consistent across reloads. So when not setting initialData, running resetQueries will give status: 'pending', data: undefined even after the query was loaded from storage. I think we should persist #initialState to storage as well.

How often does this bug happen?

Every time

Screenshots or Videos

No response

Platform

Any

Tanstack Query adapter

react-query

TanStack Query version

v5.17.9

TypeScript version

No response

Additional context

Discussion with @TkDodo https://discord.com/channels/719702312431386674/1194615111529287820

rklomp avatar Jan 11 '24 15:01 rklomp

Did you manage to find any workaround? I tried messing with the state after queries are loaded from the persistent store, but I only ended up with inconsistent states.

aitrusgit avatar Feb 21 '24 20:02 aitrusgit

I ended up using a slightly different approach that works around this limitation. But still I am having issues with options not being persisted and thus being changed after an app restart. Currently looking at https://tanstack.com/query/latest/docs/framework/react/plugins/createPersister and considering to change to this way of persisting.

rklomp avatar Feb 23 '24 08:02 rklomp

We are also running into this issue with v4. No solution yet, I tried changing the throttleTime to 1 or 0 but this has no effect. I tried deleting the data from the store itself right before .resetQueries() but it still doesn't reset the cache.

mattijsf avatar Apr 18 '24 14:04 mattijsf