Search code examples
javascriptlocal-storagereact-query

React-query v5 query data contains an empty object when using persistence


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.


Solution

  • 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:

    1. react-query starts a query, so it's in pending state.
    2. My custom dehydration logic persists the query in pending state to localStorage
    3. The user closes my page before the query resolves.
    4. The user opens my page again
    5. 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>