Turns out it happens because I had a custom logic in shouldDehydrateQuery function that was persisting queries in pending state. Steps to reproduce the problem:
- react-query starts a query, so it's in
pending state.
- My custom dehydration logic persists the query in pending state to localStorage
- The user closes my page before the query resolves.
- The user opens my page again
- The query now contains an empty object in its data.
By default, react-query only dehydrates queries with state === 'success', and you have to keep that condition in you custom dehydration logic. In order to do that, you can use defaultShouldDehydrateQuery function imported from react-query package. Example:
import {
defaultShouldDehydrateQuery,
Query,
QueryClient,
} from '@tanstack/react-query'
<PersistQueryClientProvider
client={queryClient}
persistOptions={{
persister,
maxAge: 1000 * 60 * 60 * 24 * 7,
dehydrateOptions: {
shouldDehydrateQuery: (query) => {
return (
// defaultShouldDehydrateQuery contains default logic (state === 'success')
defaultShouldDehydrateQuery(query) &&
myCustomShouldDehydrateQuery(query)
)
},
},
}}
>
{children}
</PersistQueryClientProvider>