Skip to content

Commit 131eb29

Browse files
fix(experimental): persistQueryClient and persistors (TanStack#1789)
* fix(experimental): refactor to persistQueryClient and persistor interfaces * clean up basic example
1 parent abd7f86 commit 131eb29

File tree

16 files changed

+376
-195
lines changed

16 files changed

+376
-195
lines changed
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"internal": true,
3+
"main": "../lib/createLocalStoragePersistor-experimental/index.js",
4+
"module": "../es/createLocalStoragePersistor-experimental/index.js",
5+
"types": "../types/createLocalStoragePersistor-experimental/index.d.ts"
6+
}

docs/src/manifests/manifest.json

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -303,9 +303,14 @@
303303
"heading": true,
304304
"routes": [
305305
{
306-
"title": "Persist - LocalStorage (Experimental)",
307-
"path": "/plugins/persist-localstorage",
308-
"editUrl": "/plugins/persist-localstorage.md"
306+
"title": "persistQueryClient (Experimental)",
307+
"path": "/plugins/persistQueryClient",
308+
"editUrl": "/plugins/persistQueryClient.md"
309+
},
310+
{
311+
"title": "createLocalStoragePersistor (Experimental)",
312+
"path": "/plugins/createLocalStoragePersistor",
313+
"editUrl": "/plugins/createLocalStoragePersistor.md"
309314
}
310315
]
311316
},

docs/src/pages/guides/migrating-to-react-query-3.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ Previous versions of React Query were awesome and brought some amazing new featu
2020
- Observe queries/mutations outside of React
2121
- Use the React Query core logic anywhere you want!
2222
- Bundled/Colocated Devtools via `react-query/devtools`
23-
- Cache Persistence to localstorage (experimental via `react-query/persist-localstorage-experimental`)
23+
- Cache Persistence to localstorage (experimental via `react-query/persistQueryClient-experimental` and `react-query/createLocalStoragePersistor-experimental`)
2424

2525
## Breaking Changes
2626

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
---
2+
id: createLocalStoragePersistor
3+
title: createLocalStoragePersistor (Experimental)
4+
---
5+
6+
> VERY IMPORTANT: This utility is currently in an experimental stage. This means that breaking changes will happen in minor AND patch releases. Use at your own risk. If you choose to rely on this in production in an experimental stage, please lock your version to a patch-level version to avoid unexpected breakages.
7+
8+
## Installation
9+
10+
This utility comes packaged with `react-query` and is available under the `react-query/createLocalStoragePersistor-experimental` import.
11+
12+
## Usage
13+
14+
- Import the `createLocalStoragePersistor` function
15+
- Create a new localStoragePersistor
16+
- Pass it to the [`persistQueryClient`](../persistQueryClient) function
17+
18+
```ts
19+
import { persistQueryClient } from 'react-query/persistQueryClient-experimental'
20+
import { createLocalStoragePersistor } from 'react-query/createLocalStoragePersistor-experimental'
21+
22+
const queryClient = new QueryClient({
23+
defaultOptions: {
24+
queries: {
25+
cacheTime: 1000 * 60 * 60 * 24, // 24 hours
26+
},
27+
},
28+
})
29+
30+
const localStoragePersistor = createLocalStoragePersistor()
31+
32+
persistQueryClient({
33+
queryClient
34+
persistor: localStoragePersistor,
35+
})
36+
```
37+
38+
## API
39+
40+
### `createLocalStoragePersistor`
41+
42+
Call this function (with an optional options object) to create a localStoragePersistor that you can use later with `persisteQueryClient`.
43+
44+
```js
45+
createLocalStoragePersistor(options?: CreateLocalStoragePersistorOptions)
46+
```
47+
48+
### `Options`
49+
50+
An optional object of options:
51+
52+
```js
53+
interface CreateLocalStoragePersistorOptions {
54+
/** The key to use when storing the cache to localstorage */
55+
localStorageKey?: string
56+
/** To avoid localstorage spamming,
57+
* pass a time in ms to throttle saving the cache to disk */
58+
throttleTime?: number
59+
}
60+
```
61+
62+
The default options are:
63+
64+
```js
65+
{
66+
localStorageKey = `REACT_QUERY_OFFLINE_CACHE`,
67+
throttleTime = 1000,
68+
}
69+
```

docs/src/pages/plugins/persist-localstorage.md

Lines changed: 0 additions & 97 deletions
This file was deleted.
Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
---
2+
id: persistQueryClient
3+
title: persistQueryClient (Experimental)
4+
---
5+
6+
> VERY IMPORTANT: This utility is currently in an experimental stage. This means that breaking changes will happen in minor AND patch releases. Use at your own risk. If you choose to rely on this in production in an experimental stage, please lock your version to a patch-level version to avoid unexpected breakages.
7+
8+
`persistQueryClient` is a utility for persisting the state of your queryClient and its caches for later use. Different **persistors** can be used to store your client and cache to many different storage layers.
9+
10+
## Officially Supported Persistors
11+
12+
- [createLocalStoragePersistor (Experimental)](../createLocalStoragePersistor)
13+
14+
## Installation
15+
16+
This utility comes packaged with `react-query` and is available under the `react-query/persistQueryClient-experimental` import.
17+
18+
## Usage
19+
20+
Import the `persistQueryClient` function, and pass it your `QueryClient` instance (with a `cacheTime` set), and a Persistor interface (there are multiple persistor types you can use):
21+
22+
```ts
23+
import { persistQueryClient } from 'react-query/persistQueryClient-experimental'
24+
import { createLocalStoragePersistor } from 'react-query/createLocalStoragePersistor-experimental'
25+
26+
const queryClient = new QueryClient({
27+
defaultOptions: {
28+
queries: {
29+
cacheTime: 1000 * 60 * 60 * 24, // 24 hours
30+
},
31+
},
32+
})
33+
34+
const localStoragePersistor = createLocalStoragePersistor()
35+
36+
persistQueryClient({
37+
queryClient
38+
persistor: localStoragePersistor,
39+
})
40+
```
41+
42+
**IMPORTANT** - for persist to work properly, you need to pass `QueryClient` a `cacheTime` value to override the default during hydration (as shown above).
43+
44+
If it is not set when creating the `QueryClient` instance, it will default to `300000` (5 minutes) for hydration, and the stored cache will be discarded after 5 minutes of inactivity. This is the default garbage collection behavior.
45+
46+
It should be set as the same value or higher than persistQueryClient's `maxAge` option. E.g. if `maxAge` is 24 hours (the default) then `cacheTime` should be 24 hours or higher. If lower than `maxAge`, garbage collection will kick in and discard the stored cache earlier than expected.
47+
48+
You can also pass it `Infinity` to disable garbage collection behavior entirely.
49+
50+
## How does it work?
51+
52+
As you use your application:
53+
54+
- When your query/mutation cache is updated, it will be dehydrated and stored by the persistor you provided. **By default**, this action is throttled to happen at most every 1 second to save on potentially expensive writes to a persistor, but can be customized as you see fit.
55+
56+
When you reload/bootstrap your app:
57+
58+
- Attempts to load a previously persisted dehydrated query/mutation cache from the persistor
59+
- If a cache is found that is older than the `maxAge` (which by default is 24 hours), it will be discarded. This can be customized as you see fit.
60+
61+
## Cache Busting
62+
63+
Sometimes you may make changes to your application or data that immediately invalidate any and all cached data. If and when this happens, you can pass a `buster` string option to `persistQueryClient`, and if the cache that is found does not also have that buster string, it will be discarded.
64+
65+
```ts
66+
persistQueryClient({ queryClient, persistor, buster: buildHash })
67+
```
68+
69+
## API
70+
71+
### `persistQueryClient`
72+
73+
Pass this function a `QueryClient` instance and a persistor that will persist your cache. Both are **required**
74+
75+
```ts
76+
persistQueryClient({ queryClient, persistor })
77+
```
78+
79+
### `Options`
80+
81+
An object of options:
82+
83+
```ts
84+
interface PersistQueryClientOptions {
85+
/** The QueryClient to persist */
86+
queryClient: QueryClient
87+
/** The Persistor interface for storing and restoring the cache
88+
* to/from a persisted location */
89+
persistor: Persistor
90+
/** The max-allowed age of the cache.
91+
* If a persisted cache is found that is older than this
92+
* time, it will be discarded */
93+
maxAge?: number
94+
/** A unique string that can be used to forcefully
95+
* invalidate existing caches if they do not share the same buster string */
96+
buster?: string
97+
}
98+
```
99+
100+
The default options are:
101+
102+
```ts
103+
{
104+
maxAge = 1000 * 60 * 60 * 24, // 24 hours
105+
buster = '',
106+
}
107+
```
108+
109+
## Building a Persistor
110+
111+
Persistors have the following interface:
112+
113+
```ts
114+
export interface Persistor {
115+
persistClient(persistClient: PersistedClient): Promisable<void>
116+
restoreClient(): Promisable<PersistedClient | undefined>
117+
removeClient(): Promisable<void>
118+
}
119+
```
120+
121+
Persisted Client entries have the following interface:
122+
123+
```ts
124+
export interface PersistedClient {
125+
timestamp: number
126+
buster: string
127+
cacheState: any
128+
}
129+
```
130+
131+
Satisfy all of these interfaces and you've got yourself a persistor!

package.json

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,8 @@
4848
"es",
4949
"hydration",
5050
"devtools",
51-
"persist-localstorage-experimental",
51+
"persistQueryClient-experimental",
52+
"createLocalStoragePersistor-experimental",
5253
"lib",
5354
"react",
5455
"scripts",
@@ -121,6 +122,7 @@
121122
"rollup-plugin-size": "^0.2.2",
122123
"rollup-plugin-terser": "^6.1.0",
123124
"rollup-plugin-visualizer": "^4.0.4",
125+
"type-fest": "^0.21.0",
124126
"typescript": "^4.1.2"
125127
}
126128
}

persist-localstorage-experimental/package.json

Lines changed: 0 additions & 6 deletions
This file was deleted.
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"internal": true,
3+
"main": "../lib/persistQueryClient-experimental/index.js",
4+
"module": "../es/persistQueryClient-experimental/index.js",
5+
"types": "../types/persistQueryClient-experimental/index.d.ts"
6+
}

rollup.config.js

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,14 @@ const inputSrcs = [
2020
['src/devtools/index.ts', 'ReactQueryDevtools', 'react-query-devtools'],
2121
['src/hydration/index.ts', 'ReactQueryHydration', 'react-query-hydration'],
2222
[
23-
'src/persist-localstorage-experimental/index.ts',
24-
'ReactQueryPersistLocalStorageExperimental',
25-
'persist-localstorage-experimental',
23+
'src/persistQueryClient-experimental/index.ts',
24+
'ReactQueryPersistQueryClientExperimental',
25+
'persistQueryClient-experimental',
26+
],
27+
[
28+
'src/createLocalStoragePersistor-experimental/index.ts',
29+
'ReactQueryCreateLocalStoragePersistorExperimental',
30+
'createLocalStoragePersistor-experimental',
2631
],
2732
]
2833

0 commit comments

Comments
 (0)