This persistor extends QueryCache, enabling straightforward cache persistence without needing a hydration/dehydration phase. As a result, your app gains immediate access to data, eliminating loading states.
Its main performance benefit is storing queries individually rather than persisting the entire cache with each update. This significantly boosts performance when your cache size reaches several megabytes.
⚠️ However, this approach only supports synchronous operations. If your storage relies on asynchronous get/set methods, you won't be able to use this persistor.
import { PersistentQueryCache } from 'react-query-cache-persistent'
// Your implementation. See below for examples.
const persistentQueryCache = new PersistentQueryCache({
add: (query) => {
// 1. use `query.queryHash` to query your store
const queryState =
/* from your store */
// 2. assign the value from your store to `query.state`
(query.state = queryState)
// 3. write `query.state` into your store
},
updated: (query) => {
// update your store
},
removed: (query) => {
// remove `query.queryHash` from your store
},
})
const queryClient = new QueryClient({ queryCache: persistentQueryCache })
Uses localStorage
as storage.
import { PersistentQueryCache } from 'react-query-cache-persistent'
const persistentQueryCache = new PersistentQueryCache({
add: (query) => {
const item = window.localStorage.getItem(`queryCache.${query.queryHash}`)
if (item != null) {
query.state = JSON.parse(item)
}
window.localStorage.setItem(
`queryCache.${query.queryHash}`,
JSON.stringify(query.state),
)
},
updated: (query) => {
window.localStorage.setItem(
`queryCache.${query.queryHash}`,
JSON.stringify(query.state),
)
},
removed: (query) => {
window.localStorage.removeItem(`queryCache.${query.queryHash}`)
},
})
const queryClient = new QueryClient({ queryCache: persistentQueryCache })
Uses @op-engineering/op-sqlite
as storage. But you can use any sqlite solution as long it supports synchronous get/set.
The example below writes each query as a table row into a sqlite database
MIT License.