Skip to content

Commit 261777c

Browse files
committed
feat(persistQueryClient): PersistQueryClientProvider
make sure we do not subscribe if the component unmounts before restoring has finished
1 parent 00d0ad4 commit 261777c

File tree

2 files changed

+24
-15
lines changed

2 files changed

+24
-15
lines changed

src/persistQueryClient/PersistQueryClientProvider.tsx

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -21,17 +21,14 @@ export const PersistQueryClientProvider = ({
2121
const [isHydrating, setIsHydrating] = React.useState(true)
2222
const options = React.useRef(persistOptions)
2323
React.useEffect(() => {
24-
let unsubscribe: (() => void) | undefined
24+
const [unsubscribe, promise] = persistQueryClient({
25+
...options.current,
26+
queryClient: client,
27+
})
2528

26-
async function run() {
27-
unsubscribe = await persistQueryClient({
28-
...options.current,
29-
queryClient: client,
30-
})
29+
promise.then(() => {
3130
setIsHydrating(false)
32-
}
33-
34-
void run()
31+
})
3532

3633
return unsubscribe
3734
}, [client])

src/persistQueryClient/persist.ts

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -129,14 +129,26 @@ export function persistQueryClientSubscribe(
129129

130130
/**
131131
* Restores persisted data to QueryCache and persists further changes.
132-
* (Retained for backwards compatibility)
133132
*/
134-
export async function persistQueryClient(props: PersistQueryClientOptions) {
133+
export function persistQueryClient(
134+
props: PersistQueryClientOptions
135+
): [() => void, Promise<void>] {
136+
let hasUnsubscribed = false
137+
let unsubscribe = () => {
138+
hasUnsubscribed = true
139+
}
140+
141+
let restorePromise = Promise.resolve()
142+
135143
if (typeof window !== 'undefined') {
136144
// Attempt restore
137-
await persistQueryClientRestore(props)
138-
139-
// Subscribe to changes in the query cache to trigger the save
140-
return persistQueryClientSubscribe(props)
145+
restorePromise = persistQueryClientRestore(props).then(() => {
146+
if (!hasUnsubscribed) {
147+
// Subscribe to changes in the query cache to trigger the save
148+
unsubscribe = persistQueryClientSubscribe(props)
149+
}
150+
})
141151
}
152+
153+
return [unsubscribe, restorePromise]
142154
}

0 commit comments

Comments
 (0)