I've noticed that many users of my app get unexpected runtime errors because react-query (v5.64.2) query data contains an empty object (and my backend never returns empty objects). I've also noticed it happens only with queries that are persisted (localStorage).
These errors occur randomly and I don't understand why some queries end up with an empty object ({}) in their data.
I've noticed that many users of my app get unexpected runtime errors because react-query (v5.64.2) query data contains an empty object (and my backend never returns empty objects). I've also noticed it happens only with queries that are persisted (localStorage).
These errors occur randomly and I don't understand why some queries end up with an empty object ({}) in their data.
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:
pending state.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>

