Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/sync-storage-persister-throttle-error-recovery.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/query-sync-storage-persister': patch
---

fix(query-sync-storage-persister): recover from errors thrown while persisting instead of permanently disabling future persist attempts
Original file line number Diff line number Diff line change
Expand Up @@ -189,4 +189,50 @@ describe('create persister', () => {
const restoredClient = await persister.restoreClient()
expect(restoredClient).toEqual(undefined)
})

it('should keep persisting on subsequent calls even if the retry handler throws', async () => {
const queryCache = new QueryCache()
const mutationCache = new MutationCache()
const queryClient = new QueryClient({ queryCache, mutationCache })

let setItemCalls = 0
const storage = {
getItem: () => null,
setItem: () => {
setItemCalls++
throw new Error('storage always fails')
},
removeItem: () => {},
} as any as Storage

const persister = createSyncStoragePersister({
throttleTime: 10,
storage,
retry: () => {
throw new Error('retry handler bug')
},
})

await queryClient.prefetchQuery({
queryKey: ['A'],
queryFn: () => Promise.resolve('A'),
})

const persistClient = {
buster: '',
timestamp: Date.now(),
clientState: dehydrate(queryClient),
}

// First attempt: `setItem` fails, and the `retry` handler throws while
// trying to recover. This must not leave the persister permanently stuck.
persister.persistClient(persistClient)
await sleep(20)
expect(setItemCalls).toBe(1)

// A later persist call should still be attempted, not silently dropped.
persister.persistClient(persistClient)
await sleep(20)
expect(setItemCalls).toBe(2)
})
})
11 changes: 9 additions & 2 deletions packages/query-sync-storage-persister/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,15 @@ function throttle<TArgs extends Array<any>>(
params = args
if (timer === null) {
timer = timeoutManager.setTimeout(() => {
func(...params)
timer = null
try {
func(...params)
} catch {
// Prevent an error thrown by `func` (e.g. a `retry` handler) from
// leaving `timer` stuck, which would silently disable all future
// persist attempts for the rest of the session.
} finally {
timer = null
}
}, wait)
}
}
Expand Down