最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览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.

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.

Share Improve this question edited Jan 29 at 19:58 Drew Reese 204k18 gold badges240 silver badges271 bronze badges asked Jan 29 at 9:47 MishaMisha 3413 silver badges7 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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>
发布评论

评论列表(0)

  1. 暂无评论