-
-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Add preact persist plugin #10120
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Add preact persist plugin #10120
Conversation
|
📝 WalkthroughWalkthroughA new Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
🤖 Fix all issues with AI agents
In `@packages/preact-query-persist-client/src/PersistQueryClientProvider.tsx`:
- Around line 1-2: The import order is incorrect: move the type import "import
type { VNode } from 'preact'" so it appears after the package imports from
"@tanstack/*" (specifically after any import from "@tanstack/preact-query") to
satisfy ESLint ordering; update the top of PersistQueryClientProvider.tsx so
non-type `@tanstack` imports come first and the "VNode" type import follows them.
- Around line 33-48: The finally handler calls setIsRestoring(false) even after
unmount, causing state updates on unmounted component; inside the useEffect that
references didRestore, refs.current, persistQueryClientRestore, isRestoring and
persistQueryClientSubscribe, add a mounted flag (e.g., let mounted = true) and
set mounted = false in the cleanup, then only call setIsRestoring(false) in the
persistQueryClientRestore promise chain if mounted is true; ensure the cleanup
still returns persistQueryClientSubscribe(options) when not restoring and the
mounted flag prevents setIsRestoring from running after unmount.
In `@packages/preact-query-persist-client/vite.config.ts`:
- Around line 3-5: Reorder the imports so the package JSON import appears before
the Vite type import to satisfy import/order; move "import packageJson from
'./package.json'" above "import type { UserConfig as ViteUserConfig } from
'vite'"; ensure symbols packageJson and ViteUserConfig remain unchanged and that
no other code is affected by the swap.
🧹 Nitpick comments (1)
packages/preact-query-persist-client/src/PersistQueryClientProvider.tsx (1)
14-15:onErrorcallback doesn't receive the error object.The
onErrorsignature is() => ..., so the consumer has no way to inspect or log the actual error. Consider passing the caught error through:Suggested changes:
- onError?: () => Promise<unknown> | unknown + onError?: (err: unknown) => Promise<unknown> | unknownand on line 42:
- .catch(() => refs.current.onError?.()) + .catch((err) => refs.current.onError?.(err))Note: The React counterpart has the identical issue with the same signature and error handling pattern.
| import { useEffect, useRef, useState } from 'preact/hooks' | ||
| import type { VNode } from 'preact' |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fix import order: type import from preact should follow @tanstack/* imports.
ESLint reports that the preact type import on Line 2 should occur after the @tanstack/preact-query import.
🔧 Proposed fix
import { useEffect, useRef, useState } from 'preact/hooks'
-import type { VNode } from 'preact'
import {
persistQueryClientRestore,
persistQueryClientSubscribe,
} from '@tanstack/query-persist-client-core'
import { IsRestoringProvider, QueryClientProvider } from '@tanstack/preact-query'
import type { PersistQueryClientOptions } from '@tanstack/query-persist-client-core'
import type { OmitKeyof, QueryClientProviderProps } from '@tanstack/preact-query'
+import type { VNode } from 'preact'📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| import { useEffect, useRef, useState } from 'preact/hooks' | |
| import type { VNode } from 'preact' | |
| import { useEffect, useRef, useState } from 'preact/hooks' | |
| import { | |
| persistQueryClientRestore, | |
| persistQueryClientSubscribe, | |
| } from '@tanstack/query-persist-client-core' | |
| import { IsRestoringProvider, QueryClientProvider } from '@tanstack/preact-query' | |
| import type { PersistQueryClientOptions } from '@tanstack/query-persist-client-core' | |
| import type { OmitKeyof, QueryClientProviderProps } from '@tanstack/preact-query' | |
| import type { VNode } from 'preact' |
🧰 Tools
🪛 ESLint
[error] 2-2: preact type import should occur after import of @tanstack/preact-query
(import/order)
🤖 Prompt for AI Agents
In `@packages/preact-query-persist-client/src/PersistQueryClientProvider.tsx`
around lines 1 - 2, The import order is incorrect: move the type import "import
type { VNode } from 'preact'" so it appears after the package imports from
"@tanstack/*" (specifically after any import from "@tanstack/preact-query") to
satisfy ESLint ordering; update the top of PersistQueryClientProvider.tsx so
non-type `@tanstack` imports come first and the "VNode" type import follows them.
| useEffect(() => { | ||
| const options = { | ||
| ...refs.current.persistOptions, | ||
| queryClient: props.client, | ||
| } | ||
| if (!didRestore.current) { | ||
| didRestore.current = true | ||
| persistQueryClientRestore(options) | ||
| .then(() => refs.current.onSuccess?.()) | ||
| .catch(() => refs.current.onError?.()) | ||
| .finally(() => { | ||
| setIsRestoring(false) | ||
| }) | ||
| } | ||
| return isRestoring ? undefined : persistQueryClientSubscribe(options) | ||
| }, [props.client, isRestoring]) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
🏁 Script executed:
cd . && find . -type f -name "*PersistQueryClientProvider*" | head -20Repository: TanStack/query
Length of output: 617
🏁 Script executed:
ls -la packages/Repository: TanStack/query
Length of output: 1931
🏁 Script executed:
find . -name "PersistQueryClientProvider.tsx" -type fRepository: TanStack/query
Length of output: 277
🏁 Script executed:
git ls-files | grep "PersistQueryClientProvider"Repository: TanStack/query
Length of output: 603
🏁 Script executed:
git ls-files "**/*PersistQueryClientProvider*"Repository: TanStack/query
Length of output: 603
🏁 Script executed:
find packages -type f -name "*.tsx" | grep -i providerRepository: TanStack/query
Length of output: 855
🏁 Script executed:
find . -type f -name "*.tsx" -o -name "*.ts" | xargs grep -l "PersistQueryClientProvider" 2>/dev/nullRepository: TanStack/query
Length of output: 953
🏁 Script executed:
tree -L 3 -d 2>/dev/null || find . -maxdepth 3 -type d | head -30Repository: TanStack/query
Length of output: 6546
🏁 Script executed:
pwd && ls -laRepository: TanStack/query
Length of output: 2437
🏁 Script executed:
find . -path "*/preact-query-persist-client/*" -type fRepository: TanStack/query
Length of output: 623
🏁 Script executed:
rg "didRestore.current" -t tsx -t tsRepository: TanStack/query
Length of output: 85
🏁 Script executed:
git ls-files | wc -l && git ls-files | grep -i providerRepository: TanStack/query
Length of output: 2578
🏁 Script executed:
git ls-files | grep "\.tsx$"Repository: TanStack/query
Length of output: 17194
🏁 Script executed:
git log --oneline --all | head -5Repository: TanStack/query
Length of output: 340
🏁 Script executed:
git ls-files --full-name | sortRepository: TanStack/query
Length of output: 50371
🏁 Script executed:
git ls-files --full-name | grep -i persistRepository: TanStack/query
Length of output: 9283
🏁 Script executed:
find . -type f -name "*.tsx" | wc -lRepository: TanStack/query
Length of output: 61
🏁 Script executed:
rg "useEffect" --type tsx --type ts | grep -i "persistquery\|restore" -A 5Repository: TanStack/query
Length of output: 85
🏁 Script executed:
rg "persistQueryClientRestore"Repository: TanStack/query
Length of output: 2830
🏁 Script executed:
git ls-files | head -100Repository: TanStack/query
Length of output: 4804
🏁 Script executed:
cat /dev/null && pwdRepository: TanStack/query
Length of output: 76
🏁 Script executed:
git remote -v 2>/dev/null || echo "No git remote found"Repository: TanStack/query
Length of output: 174
🏁 Script executed:
git rev-parse --show-toplevel 2>/dev/null || echo "Not a git repo"Repository: TanStack/query
Length of output: 76
🏁 Script executed:
test -f packages/preact-query-persist-client/src/PersistQueryClientProvider.tsx && echo "File exists" || echo "File not found"Repository: TanStack/query
Length of output: 69
🏁 Script executed:
find . -iname "*react*query*persist*" -o -iname "*preact*query*persist*" 2>/dev/nullRepository: TanStack/query
Length of output: 134
🌐 Web query:
TanStack query persist client PersistQueryClientProvider restore unmount
💡 Result:
In TanStack Query (v5), restoration/persistence works like this:
persistQueryClient({ ... })does two things: (1) async restore of the persisted cache, then (2) subscribes to cache changes and returns an unsubscribe function. If you call it outside React, you can’t reliably unsubscribe and you can also get restore-vs-fetch race conditions. [1]PersistQueryClientProviderexists specifically to solve those lifecycle issues: it subscribes/unsubscribes with the React component lifecycle, and it also prevents queries from starting network fetching while restore is in progress (queries render, but are held infetchingState: 'idle'until restore completes). [1]onSuccessis called when the initial restore finishes; if it returns a Promise, the provider will keep “restoring” true until that Promise resolves (useful forresumePausedMutations). [1]
What happens on unmount/remount?
- If
PersistQueryClientProviderunmounts, it will unsubscribe from persistence syncing (that’s the point of using it). [1] - If it mounts again, it will run the restore again and re-subscribe. (So in most apps, you want this provider mounted once at the app root.)
Manual pattern (if you’re not using PersistQueryClientProvider)
Use explicit restore + subscribe in an effect, and cleanup on unmount:
import { useEffect } from 'react'
import {
persistQueryClientRestore,
persistQueryClientSubscribe,
} from '@tanstack/react-query-persist-client'
function usePersistedQueryClient({ queryClient, persister, buster, maxAge }: any) {
useEffect(() => {
let unsub: (() => void) | undefined
;(async () => {
await persistQueryClientRestore({ queryClient, persister, buster, maxAge })
unsub = persistQueryClientSubscribe({ queryClient, persister, buster })
})()
return () => {
unsub?.()
}
}, [queryClient, persister, buster, maxAge])
}This mirrors what the provider is designed to manage for you. [1]
Source
[1] TanStack Query docs: persistQueryClient / PersistQueryClientProvider lifecycle + restoring behavior (tanstack.dev)
Citations:
🏁 Script executed:
find . -type f \( -name "*.tsx" -o -name "*.ts" \) 2>/dev/nullRepository: TanStack/query
Length of output: 50371
🏁 Script executed:
file $(git ls-files | head -1) 2>/dev/nullRepository: TanStack/query
Length of output: 42
🏁 Script executed:
git diff-tree --no-commit-id --name-only -r HEAD 2>/dev/null | head -20Repository: TanStack/query
Length of output: 40
🌐 Web query:
TanStack query persist client PersistQueryClientProvider.tsx github
💡 Result:
The source for PersistQueryClientProvider lives in the TanStack Query monorepo here (GitHub):
https://github.com/TanStack/query/blob/main/packages/react-query-persist-client/src/PersistQueryClientProvider.tsx
This component is part of @tanstack/react-query-persist-client and is the recommended React wrapper around persistQueryClient so restore/subscribe/unsubscribe happens in the React lifecycle and queries don’t race-fetch while the cache is restoring. [1][2]
Sources: [1], [2]
🏁 Script executed:
git ls-files packages/ 2>/dev/null || echo "Checking without git"; ls -la packages/ 2>/dev/null || echo "No packages dir"Repository: TanStack/query
Length of output: 44438
🏁 Script executed:
rg "useEffect.*didRestore"Repository: TanStack/query
Length of output: 40
🌐 Web query:
TanStack "PersistQueryClientProvider" preact implementation
💡 Result:
There’s no special TanStack Query “preact” build for PersistQueryClientProvider—you use the normal React packages, and run them through Preact’s React-compat layer (preact/compat).
1) Make react resolve to preact/compat
One simple approach is a package alias so anything importing react gets @preact/compat instead (works in Node tooling too): (bret.io)
// package.json
{
"dependencies": {
"preact": "^10.0.0",
"@tanstack/react-query": "^5.0.0",
"@tanstack/react-query-persist-client": "^5.0.0",
"@tanstack/query-sync-storage-persister": "^5.0.0",
"react": "npm:`@preact/compat`@^18.0.0"
}
}(Alternatively, you can do a bundler alias to map react -> preact/compat.)
2) Use PersistQueryClientProvider exactly like in React
PersistQueryClientProvider is provided by @tanstack/react-query-persist-client and is designed to manage restore + subscribe/unsubscribe via the component lifecycle. (tanstack.dev)
localStorage (sync) example (Preact entry)
// main.tsx (or similar)
import { render } from 'preact'
import { QueryClient } from '@tanstack/react-query'
import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client'
import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister'
import { App } from './app'
const queryClient = new QueryClient({
defaultOptions: {
queries: {
gcTime: 1000 * 60 * 60 * 24, // 24h
},
},
})
const persister = createSyncStoragePersister({
storage: typeof window !== 'undefined' ? window.localStorage : undefined,
})
render(
<PersistQueryClientProvider
client={queryClient}
persistOptions={{ persister }}
>
<App />
</PersistQueryClientProvider>,
document.getElementById('app')!,
)createSyncStoragePersister is the official helper for localStorage/sessionStorage. (tanstack.com)
Citations:
- 1: https://bret.io/blog/2026/simple-tanstack-query-in-preact/?utm_source=openai
- 2: https://tanstack.dev/query/latest/docs/framework/react/plugins/persistQueryClient?utm_source=openai
- 3: https://tanstack.com/query/latest/docs/framework/react/plugins/createSyncStoragePersister?utm_source=openai
🏁 Script executed:
git config --local remote.origin.url 2>/dev/null || git config --global user.name 2>/dev/null || echo "Git config unavailable"Repository: TanStack/query
Length of output: 95
🏁 Script executed:
rg "\.finally\(\(" -t tsx -A 2Repository: TanStack/query
Length of output: 85
🌐 Web query:
TanStack query repository persist client PersistQueryClientProvider
💡 Result:
PersistQueryClientProvider lives in the TanStack Query monorepo under packages/react-query-persist-client (source: packages/react-query-persist-client/src/PersistQueryClientProvider.tsx). [3]
What it does
Use PersistQueryClientProvider (from @tanstack/react-query-persist-client) instead of QueryClientProvider so that:
- the persisted cache is restored asynchronously before queries start fetching (avoids restore/fetch race conditions)
- the persist “subscription” is correctly subscribed/unsubscribed with the React lifecycle. [1]
Install (typical)
@tanstack/react-query-persist-client- a persister, e.g.
@tanstack/query-sync-storage-persister(weblocalStorage) or@tanstack/query-async-storage-persister(AsyncStorage / async). [1][2]
Minimal example (web localStorage)
import { QueryClient } from '@tanstack/react-query'
import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client'
import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister'
const queryClient = new QueryClient({
defaultOptions: {
queries: {
gcTime: 1000 * 60 * 60 * 24, // important for persistence/hydration
},
},
})
const persister = createSyncStoragePersister({
storage: window.localStorage,
})
export function Root() {
return (
<PersistQueryClientProvider
client={queryClient}
persistOptions={{ persister }}
// optional:
// onSuccess={() => queryClient.resumePausedMutations()}
>
<App />
</PersistQueryClientProvider>
)
}PersistQueryClientProvider props:
- everything
QueryClientProvidersupports, plus:persistOptions(same options aspersistQueryClientminus thequeryClient)onSuccess/onErrorcallbacks for the initial restore. [1]
If you tell me your target (web vs React Native) and TanStack Query major version (v4 vs v5), I can tailor the exact packages/imports.
🌐 Web query:
site:github.com "persistQueryClientRestore" preact
💡 Result:
Your GitHub query (site:github.com "persistQueryClientRestore" preact) doesn’t surface any Preact-specific usage/examples of persistQueryClientRestore. Instead, persistQueryClientRestore is a TanStack Query persistence utility (it restores/hydrates a previously persisted cache into a QueryClient) and is not inherently tied to React/Preact at the function level. [1]
If you’re looking for “Preact + TanStack Query” support, TanStack Query has an open “Feat: Preact Adapter” PR (#9935), which is the most directly relevant GitHub hit connecting Preact to the TanStack Query ecosystem. [2]
Sources: [1], [2]
🏁 Script executed:
find . -type f 2>/dev/null | wc -l && find . -type f 2>/dev/null | head -50Repository: TanStack/query
Length of output: 3459
🏁 Script executed:
wc -l packages/preact-query-persist-client/src/PersistQueryClientProvider.tsxRepository: TanStack/query
Length of output: 132
🏁 Script executed:
cat packages/react-query-persist-client/src/PersistQueryClientProvider.tsxRepository: TanStack/query
Length of output: 1803
🏁 Script executed:
# Let's check for any unmount handling or cleanup in both files
rg "return.*=>|useEffect.*cleanup" packages/react-query-persist-client/src/PersistQueryClientProvider.tsx packages/preact-query-persist-client/src/PersistQueryClientProvider.tsxRepository: TanStack/query
Length of output: 40
🏁 Script executed:
grep -A 10 "unmount\|cleanup\|cancel" packages/react-query-persist-client/src/__tests__/PersistQueryClientProvider.test.tsxRepository: TanStack/query
Length of output: 40
Guard setIsRestoring(false) against state updates after unmount.
The persistQueryClientRestore promise chain executes its finally block and calls setIsRestoring(false) even if the component unmounts before the restore settles. This causes a React "Cannot update an unmounted component" warning. Add a mounted flag to the cleanup function:
♻️ Suggested fix
React.useEffect(() => {
+ let isMounted = true
const options = {
...refs.current.persistOptions,
queryClient: props.client,
}
if (!didRestore.current) {
didRestore.current = true
persistQueryClientRestore(options)
.then(() => refs.current.onSuccess?.())
.catch(() => refs.current.onError?.())
.finally(() => {
+ if (isMounted) {
setIsRestoring(false)
+ }
})
}
- return isRestoring ? undefined : persistQueryClientSubscribe(options)
+ return () => {
+ isMounted = false
+ return isRestoring ? undefined : persistQueryClientSubscribe(options)
+ }
}, [props.client, isRestoring])🤖 Prompt for AI Agents
In `@packages/preact-query-persist-client/src/PersistQueryClientProvider.tsx`
around lines 33 - 48, The finally handler calls setIsRestoring(false) even after
unmount, causing state updates on unmounted component; inside the useEffect that
references didRestore, refs.current, persistQueryClientRestore, isRestoring and
persistQueryClientSubscribe, add a mounted flag (e.g., let mounted = true) and
set mounted = false in the cleanup, then only call setIsRestoring(false) in the
persistQueryClientRestore promise chain if mounted is true; ensure the cleanup
still returns persistQueryClientSubscribe(options) when not restoring and the
mounted flag prevents setIsRestoring from running after unmount.
| import type { UserConfig as ViteUserConfig } from 'vite' | ||
|
|
||
| import packageJson from './package.json' |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fix import order: ./package.json should be imported before the type import from vite.
ESLint flags this as an import/order violation.
Proposed fix
-import { defineConfig } from 'vitest/config'
-import type { UserConfig as ViteUserConfig } from 'vite'
-
-import packageJson from './package.json'
+import { defineConfig } from 'vitest/config'
+import packageJson from './package.json'
+import type { UserConfig as ViteUserConfig } from 'vite'🧰 Tools
🪛 ESLint
[error] 5-5: ./package.json import should occur before type import of vite
(import/order)
🤖 Prompt for AI Agents
In `@packages/preact-query-persist-client/vite.config.ts` around lines 3 - 5,
Reorder the imports so the package JSON import appears before the Vite type
import to satisfy import/order; move "import packageJson from './package.json'"
above "import type { UserConfig as ViteUserConfig } from 'vite'"; ensure symbols
packageJson and ViteUserConfig remain unchanged and that no other code is
affected by the swap.
🎯 Changes
This adds the persist plugin, similar to how other integrations have the plugin.
✅ Checklist
pnpm run test:pr.🚀 Release Impact
This is the initial release of the package
Summary by CodeRabbit
New Features
Documentation