0

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.

1 Answer 1

0

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.