diff --git a/.changeset/react-query-pluggable.md b/.changeset/react-query-pluggable.md new file mode 100644 index 00000000000..7d2e8ea0f4c --- /dev/null +++ b/.changeset/react-query-pluggable.md @@ -0,0 +1,8 @@ +--- +'@tanstack/query-core': minor +'@tanstack/react-query-pluggable': minor +--- + +Add an experimental ESM-only React Query adapter backed by `@tanstack/query-core`. Apps can import polling, selection, placeholder data, and serial mutation queues where they use them. Use `useQuery(query(options))` for a regular read and `useQuery(suspenseQuery(options))` to suspend on the same cache. Compose `infiniteQuery(options)` with the same hook and Suspense policy to read pages. For imperative fetching, import `fetchInfiniteQuery(client, options)`. Client operations are named functions with the client as their first argument, including `getQueryData(client, key)` and `invalidateQueries(client, filters)`. + +Mutation hooks acquire a cache on first use. For direct access, import `getMutationCache` and call `getMutationCache(client)`. Clients configured with a custom cache return that instance. diff --git a/.github/workflows/react-query-bundle-size.yml b/.github/workflows/react-query-bundle-size.yml new file mode 100644 index 00000000000..f0d3c8a43f8 --- /dev/null +++ b/.github/workflows/react-query-bundle-size.yml @@ -0,0 +1,100 @@ +name: React Query app bundle size + +on: + pull_request: + paths: + - '.github/workflows/react-query-bundle-size.yml' + - 'integrations/react/bundle-size/**' + - 'packages/query-core/**' + - 'packages/react-query/**' + - 'packages/react-query-pluggable/**' + - 'scripts/getTsdownConfig.js' + - '.nvmrc' + - 'package.json' + - 'pnpm-lock.yaml' + - 'pnpm-workspace.yaml' + +concurrency: + group: ${{ github.workflow }}-${{ github.event.number }} + cancel-in-progress: true + +permissions: {} + +jobs: + measure: + runs-on: ubuntu-latest + permissions: + contents: read + outputs: + report: ${{ steps.measure.outputs.report }} + analyzer_url: ${{ steps.analyzer.outputs.artifact-url }} + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + ref: ${{ github.event.pull_request.head.sha }} + persist-credentials: false + - uses: TanStack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 + - name: Check out the unmodified PR base + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + ref: ${{ github.event.pull_request.base.sha }} + path: .bundle-base + persist-credentials: false + - name: Install and build the baseline adapter + working-directory: .bundle-base + run: | + pnpm --filter root --filter '@tanstack/react-query...' install --frozen-lockfile + pnpm --filter '@tanstack/react-query...' run build + - name: Build workspace dependencies + run: pnpm --filter '@tanstack/query-integration-react-bundle-size^...' run build + - name: Build and measure production apps + id: measure + env: + QUERY_BASE_CHECKOUT: ${{ github.workspace }}/.bundle-base + working-directory: integrations/react/bundle-size + run: | + pnpm run measure + cat dist/report.md >> "$GITHUB_STEP_SUMMARY" + jq -Rsr '"report=" + tojson' dist/report.md >> "$GITHUB_OUTPUT" + - name: Install Chromium + working-directory: integrations/react/bundle-size + run: pnpm run browser:install + - name: Exercise production apps in Chromium + working-directory: integrations/react/bundle-size + run: pnpm run test:browser + - name: Upload interactive bundle treemaps + id: analyzer + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: react-query-bundle-analyzer + path: integrations/react/bundle-size/dist/analyzer/ + if-no-files-found: error + retention-days: 30 + comment: + if: github.event.pull_request.head.repo.full_name == github.repository + needs: measure + runs-on: ubuntu-latest + permissions: + pull-requests: write + steps: + - name: Update bundle size comment + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + PR_NUMBER: ${{ github.event.number }} + REPORT: ${{ needs.measure.outputs.report }} + ANALYZER_URL: ${{ needs.measure.outputs.analyzer_url }} + run: | + comments="repos/$REPO/issues/$PR_NUMBER/comments" + marker='' + id=$(gh api --paginate --slurp "$comments?per_page=100" | + jq -r --arg marker "$marker" '[.[][] | select(.user.login == "github-actions[bot]" and (.body | startswith($marker)))][0].id // empty') + endpoint="$comments" + method=POST + if [[ -n "$id" ]]; then + endpoint="repos/$REPO/issues/comments/$id" + method=PATCH + fi + jq -n --arg marker "$marker" --argjson report "$REPORT" --arg analyzer "$ANALYZER_URL" \ + '{body: ($marker + "\n" + $report + "\n[Download the interactive bundle treemaps](" + $analyzer + ")")}' | + gh api --silent --method "$method" "$endpoint" --input - diff --git a/integrations/react/bundle-size/README.md b/integrations/react/bundle-size/README.md new file mode 100644 index 00000000000..3f70a12fa98 --- /dev/null +++ b/integrations/react/bundle-size/README.md @@ -0,0 +1,51 @@ +# React Query app bundle size + +This workspace builds four browser apps against each adapter’s public package entry point. The read-only app fetches a book list with `useQuery(options)` in v6 and `useQuery(query(options))` in the pluggable adapter. The paginated app uses the query, infinite-query and mutation option factories to fetch additional pages and save bookmarks in browser storage. The polling app refreshes regular and infinite queries, both with and without Suspense. The pluggable app calls `useQuery` with `query(options)`, `infiniteQuery(options)`, `suspenseQuery(options)` or `suspenseQuery(infiniteQuery(options))` for each subscriber. The browser test holds the first responses until both dedicated Suspense boundaries show their fallbacks, then checks the resolved data and subsequent refetches. The options app keeps the previous page while fetching, selects the displayed titles, saves bookmarks in a serial scope, and invalidates the bookmark list. Each app uses the default client. The original adapter accepts a numeric interval. The pluggable adapter imports its interval scheduler through the `refetchInterval` option helper. + +CI builds the original adapter and its dependencies from the PR's base commit. The experimental `@tanstack/react-query-pluggable` adapter, its `@tanstack/query-core` dependency, the app code, the bundler and both React packages come from the PR head. The report records both commit IDs. + +## What the PR comment measures + +The opening table compares the gzipped Query runtime for each workload. It shows both package sizes in bytes and the signed change in bytes and percent relative to v6. Expand either detail table to see the absolute minified, gzip and Brotli sizes. + +1. **Query runtime used by the app.** Vite builds the same HTML and React entry points with React, React DOM and their subpaths external. Rolldown groups the adapter’s retained modules into one ESM chunk, including all retained `@tanstack/query-core` modules from the same checkout as that adapter. The app and its workload-specific helpers stay in a separate entry chunk. The benchmark directly measures the minified Query chunk, including its ESM import and export bindings. Its gzip and Brotli sizes describe compressing this chunk on its own. Percentages use the original adapter’s isolated chunk for that workload and encoding. +2. **Whole production app.** Vite builds the deployable application with its ordinary chunk layout, including React, React DOM, the app and the adapter. Each percentage uses the original adapter’s full app for that workload and encoding. Compressing these complete chunks accounts for compression shared between the app and its dependencies. + +Both tables show the emitted JS byte length, gzip at level 9 and Brotli at quality 11. The benchmark compresses each emitted JS chunk independently and sums the lengths. HTML, source maps and analysis reports are excluded. + +The pluggable options app calls `invalidateQueries(client, { queryKey: ['bookmarks'] })`. Every named client operation takes the client first. The benchmark checks retained exports to verify that importing `QueryClient` leaves out `fetchQuery`, `setQueryData` and bulk operations, and that each named operation is available when imported. + +For each app, the benchmark verifies that the isolated Query chunk contains the same retained Query module IDs and exports as the whole production app and imports only React peer entry points. Feature checks cover modules in both the pluggable adapter and its shared core. Both the read-only and polling apps construct a `QueryClient` and use queries. The pluggable build must retain the query cache and observer and exclude the mutation cache, mutation and mutation observer. Both bookmark apps call `useMutation` and must retain all three mutation modules. The read-only app excludes the Suspense builder and policy. The polling app retains both. Pagination and polling retain the infinite query builder and observer. All four hook-driven apps exclude the imperative `fetchInfiniteQuery` implementation. Additional checks cover polling, infinite queries, selection, placeholder data, serial queues and bulk cache operations. Individual public export probes check that selection, placeholder data and serial queues can be removed independently. The React hydration boundary only restores queries. The universal `hydrate` also restores serial queues from saved mutations. + +The PR comment links to the workflow artifact containing an interactive HTML bundle analyzer for each package and workload. Open `dist/analyzer//.html` locally after running the benchmark. Select the `query-runtime` chunk to explore its constituent sources. The treemap shows module contributions from source maps. The tables use actual compressed chunk bytes. + +## Run locally + +For a comparison within the current checkout, run from the repository root after installing workspace dependencies: + +```sh +pnpm --filter '@tanstack/query-integration-react-bundle-size^...' run build +pnpm --filter @tanstack/query-integration-react-bundle-size run measure +``` + +To reproduce the CI comparison, use a clean worktree of the base commit. Replace `BASE_SHA` with the base commit from the report. + +```sh +git worktree add --detach ../query-bundle-base BASE_SHA +pnpm --dir ../query-bundle-base --filter root --filter '@tanstack/react-query...' install --frozen-lockfile +pnpm --dir ../query-bundle-base --filter '@tanstack/react-query...' run build +QUERY_BASE_CHECKOUT="$PWD/../query-bundle-base" pnpm --filter @tanstack/query-integration-react-bundle-size run measure +``` + +Read the summary and detailed tables in `integrations/react/bundle-size/dist/report.md`. Serve a directory under `dist//` to try the built app. + +Run the eight production app scenarios in Chromium after measuring: + +```sh +cd integrations/react/bundle-size +pnpm exec playwright install chromium +pnpm test:browser +pnpm test:browser:ui +``` + +The last command starts Vitest in watch mode with a browser UI for inspecting and rerunning each adapter’s scenarios. diff --git a/integrations/react/bundle-size/analyze.mjs b/integrations/react/bundle-size/analyze.mjs new file mode 100644 index 00000000000..9b3984cbc85 --- /dev/null +++ b/integrations/react/bundle-size/analyze.mjs @@ -0,0 +1,19 @@ +import path from 'node:path' +import { visualizer } from 'rollup-plugin-visualizer' + +export function adapterTreemap(screen, packageName) { + const name = packageName.split('/')[1] + return visualizer({ + filename: path.join( + import.meta.dirname, + 'dist/analyzer', + screen, + name + '.html', + ), + title: `${packageName} · ${screen}`, + template: 'treemap', + sourcemap: true, + // Make source names comparable across the PR base and head checkouts. + projectRoot: /^.*\/(?=(?:packages|integrations)\/)/, + }) +} diff --git a/integrations/react/bundle-size/browser/apps.test.js b/integrations/react/bundle-size/browser/apps.test.js new file mode 100644 index 00000000000..996a869c909 --- /dev/null +++ b/integrations/react/bundle-size/browser/apps.test.js @@ -0,0 +1,136 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { commands } from 'vitest/browser' + +const adapters = ['react-query', 'react-query-pluggable'] + +function mountApp(scenario, adapter) { + const frame = document.createElement('iframe') + frame.title = adapter + frame.src = `/${scenario}/${adapter}/index.html` + document.body.append(frame) + return frame +} + +async function openApp(scenario, adapter) { + const frame = mountApp(scenario, adapter) + await expect + .poll(() => frame.contentDocument?.querySelector('li')?.textContent) + .toContain('Middlemarch') + return frame.contentDocument +} + +afterEach(() => { + document.querySelector('iframe')?.remove() + localStorage.removeItem('bookmark') + localStorage.removeItem('bookmarks') +}) + +describe.each(adapters)('@tanstack/%s', (adapter) => { + it('renders a fetched reading list', async () => { + const app = await openApp('query', adapter) + expect( + Array.from(app.querySelectorAll('li'), (row) => row.textContent), + ).toEqual(['Middlemarch', 'Persuasion']) + }) + + it('loads the next page and saves a bookmark', async () => { + const app = await openApp('paginated', adapter) + const more = Array.from(app.querySelectorAll('button')).find( + (button) => button.textContent === 'Load more', + ) + more.click() + await expect.poll(() => app.querySelectorAll('li').length).toBe(4) + const third = app.querySelectorAll('li')[2] + expect(third.textContent).toContain('Villette') + third.querySelector('button').click() + await expect + .poll(() => app.body.textContent) + .toContain('Bookmarked: Villette') + expect(localStorage.getItem('bookmark')).toBe('Villette') + }) + + it('retains the previous selection, queues bookmarks and refreshes the cache', async () => { + const app = await openApp('options', adapter) + const view = app.defaultView + const originalFetch = view.fetch.bind(view) + const gate = Promise.withResolvers() + view.fetch = async (...args) => { + if (String(args[0]).endsWith('books-2.json')) await gate.promise + return originalFetch(...args) + } + const button = (label) => + Array.from(app.querySelectorAll('button')).find( + (item) => item.textContent === label, + ) + try { + button('Next page').click() + await expect + .poll(() => app.querySelector('[role="status"]')?.textContent) + .toBe('Showing the previous page') + expect(app.querySelector('ul').textContent).toContain('Middlemarch') + } finally { + gate.resolve() + view.fetch = originalFetch + } + await expect + .poll(() => app.querySelector('ul').textContent) + .toContain('Villette') + button('Bookmark this page').click() + await expect + .poll(() => app.body.textContent) + .toContain('Bookmarks: Villette, North and South') + expect( + Array.from(app.querySelectorAll('ol li'), (item) => item.textContent), + ).toEqual([ + 'Saving Villette', + 'Saved Villette', + 'Saving North and South', + 'Saved North and South', + ]) + }) + + it('periodically refetches regular, infinite and suspense queries', async () => { + await commands.holdPollingBooks(adapter) + const frame = mountApp('polling', adapter) + try { + await commands.waitForPollingRequest(adapter) + await expect + .poll(() => + Array.from( + frame.contentDocument.querySelectorAll('[role="status"]'), + (element) => element.textContent, + ), + ) + .toEqual(['Loading suspense query…', 'Loading suspense pages…']) + } finally { + await commands.releasePollingBooks(adapter) + } + const app = frame.contentDocument + await expect + .poll(() => + Array.from(app.querySelectorAll('li'), (item) => + item.textContent.includes('Middlemarch'), + ), + ) + .toEqual([true, true, true, true]) + const timestamps = () => + Array.from(app.querySelectorAll('time'), (time) => time.dateTime) + await expect.poll(() => timestamps().length).toBe(4) + // Two successive refreshes for every hook distinguish interval polling from a mount refetch. + for (let refresh = 0; refresh < 2; refresh++) { + const previous = timestamps() + await expect + .poll( + () => { + const current = timestamps() + return ( + current.length === 4 && + current.every((value, index) => value > previous[index]) + ) + }, + { timeout: 4000 }, + ) + .toBe(true) + } + }) +}) diff --git a/integrations/react/bundle-size/index.html b/integrations/react/bundle-size/index.html new file mode 100644 index 00000000000..43cc6a8fab6 --- /dev/null +++ b/integrations/react/bundle-size/index.html @@ -0,0 +1,12 @@ + + + + + + Reading list + + +
+ + + diff --git a/integrations/react/bundle-size/measure.mjs b/integrations/react/bundle-size/measure.mjs new file mode 100644 index 00000000000..e4197cc79e3 --- /dev/null +++ b/integrations/react/bundle-size/measure.mjs @@ -0,0 +1,528 @@ +import assert from 'node:assert/strict' +import { execFileSync } from 'node:child_process' +import { realpath, writeFile } from 'node:fs/promises' +import path from 'node:path' +import { brotliCompressSync, constants, gzipSync } from 'node:zlib' +import { build, normalizePath } from 'vite' +import { adapterTreemap } from './analyze.mjs' + +const root = import.meta.dirname +const checkout = path.resolve(root, '../../..') +const baseCheckout = process.env.QUERY_BASE_CHECKOUT + ? await realpath(process.env.QUERY_BASE_CHECKOUT) + : undefined +const basePackage = + baseCheckout && path.join(baseCheckout, 'packages/react-query') +const baseline = '@tanstack/react-query' +const pluggable = '@tanstack/react-query-pluggable' +const packages = [baseline, pluggable] +const workloads = [ + { screen: 'query', title: 'Read-only list' }, + { screen: 'paginated', title: 'Paginated bookmarks' }, + { + screen: 'options', + title: 'Selection, serial bookmarks and invalidation', + }, + { + screen: 'polling', + title: 'Polling', + }, +] + +const otherFrameworks = [ + /\/(?:packages|node_modules\/@tanstack)\/(?:angular|lit|preact|solid|svelte|vue)-query[^/]*\//, + /\/node_modules\/(?:@angular|@lit|@vue|lit|lit-element|lit-html|preact|solid-js|svelte|vue)\//, +] + +function runtimeOwners(directory, packageName) { + return [packageName.split('/')[1], 'query-core'].map( + (name) => + normalizePath(path.join(directory, 'packages', name, 'build')) + '/', + ) +} + +const pluggableOwners = runtimeOwners(checkout, pluggable) +function rendersFeature(id, feature) { + return ( + id.endsWith(`/${feature}.js`) && + pluggableOwners.some((dir) => id.startsWith(dir)) + ) +} + +async function buildApp(packageName, screen, belongsToAdapter) { + const outDir = path.join(root, 'dist', screen, packageName.split('/')[1]) + const result = await build({ + root, + base: './', + configFile: false, + mode: 'production', + logLevel: 'warn', + plugins: [ + ...(belongsToAdapter ? [adapterTreemap(screen, packageName)] : []), + { + name: 'resolve-benchmark-adapter', + enforce: 'pre', + resolveId(id, importer) { + if (id !== '#adapter') return + // Resolve the public browser export using the requested checkout's package scope. + const from = + packageName === baseline && basePackage + ? path.join(basePackage, 'package.json') + : importer + return this.resolve(packageName, from, { skipSelf: true }) + }, + }, + ], + resolve: { + dedupe: ['react', 'react-dom'], + alias: { + '#query-hooks': path.join( + root, + 'src', + packageName === pluggable ? 'pluggable-query.js' : 'v6-query.js', + ), + '#polling-option': path.join( + root, + 'src', + packageName === pluggable + ? 'pluggable-interval.js' + : 'numeric-interval.js', + ), + '#feature-options': path.join( + root, + 'src', + packageName === pluggable ? 'pluggable-options.js' : 'v6-options.js', + ), + '#screen': path.join(root, 'src', `${screen}.jsx`), + }, + }, + build: { + outDir, + write: !belongsToAdapter, + sourcemap: belongsToAdapter ? 'hidden' : false, + reportCompressedSize: false, + // All modules in these apps execute on the client. + rolldownOptions: { + checks: { moduleLevelDirective: false }, + ...(belongsToAdapter && { + external: reactPeer, + output: { + codeSplitting: { + groups: [ + { + name: 'query-runtime', + test: belongsToAdapter, + includeDependenciesRecursively: false, + }, + ], + }, + }, + }), + }, + }, + }) + const chunks = result.output.filter((output) => output.type === 'chunk') + if (!chunks.some((chunk) => chunk.isEntry)) { + throw new Error(`Missing browser entry chunk for ${packageName}`) + } + return chunks +} + +function renderedModules(chunks) { + return chunks.flatMap((chunk) => + Object.entries(chunk.modules).filter( + ([, module]) => module.renderedLength > 0, + ), + ) +} + +// Each bulk operation may retain the other public operations it calls. +const bulkOperations = { + getQueriesData: [], + setQueriesData: ['setQueryData'], + removeQueries: [], + resetQueries: ['refetchQueries'], + cancelQueries: [], + invalidateQueries: ['refetchQueries'], + refetchQueries: [], +} + +function checkClientOperations(modules, workload, required) { + const operations = new Set( + modules.flatMap(([id, module]) => { + if (rendersFeature(id, 'cacheOperations')) return module.renderedExports + if (rendersFeature(id, 'queryClient')) { + return module.renderedExports.filter( + (name) => name === 'fetchQuery' || name === 'setQueryData', + ) + } + return [] + }), + ) + const allowed = [required, ...(bulkOperations[required] ?? [])] + for (const name of operations) { + assert( + allowed.includes(name), + `${workload} retained unused client operation ${name}`, + ) + } + if (required) + assert(operations.has(required), `${workload} is missing ${required}`) +} + +function checkApp(chunks, packageName, screen) { + const modules = renderedModules(chunks).map(([id]) => id) + if ( + packageName === baseline && + basePackage && + !modules.some((id) => id.startsWith(normalizePath(basePackage) + '/build/')) + ) { + throw new Error( + `Missing built @tanstack/react-query from base checkout ${basePackage}`, + ) + } + if (packageName === pluggable) { + const foreignRuntime = modules.find((id) => + otherFrameworks.some((pattern) => pattern.test(id)), + ) + if (foreignRuntime) { + throw new Error( + `${packageName} bundled unexpected runtime code: ${foreignRuntime}`, + ) + } + if ( + chunks.some((chunk) => + chunk.moduleIds.some((id) => id.endsWith('/build/runtime/index.js')), + ) + ) { + throw new Error( + `${packageName} included an internal runtime barrel in the app`, + ) + } + const usesMutations = screen === 'paginated' || screen === 'options' + const features = { + queryClient: true, + queryCache: true, + query: true, + queryObserver: true, + mutationCache: usesMutations, + mutation: usesMutations, + mutationObserver: usesMutations, + suspenseQuery: screen === 'polling', + suspense: screen === 'polling', + refetchInterval: screen === 'polling', + fetchInfiniteQuery: false, + infiniteQuery: screen === 'paginated' || screen === 'polling', + infiniteQueryObserver: screen === 'paginated' || screen === 'polling', + infiniteQueryBehavior: screen === 'paginated' || screen === 'polling', + select: screen === 'options', + placeholderData: screen === 'options', + serialScope: screen === 'options', + cacheOperations: screen === 'options', + } + for (const [feature, expected] of Object.entries(features)) { + const included = modules.some((id) => rendersFeature(id, feature)) + if (included !== expected) { + throw new Error( + `Unexpected ${feature} implementation in ${screen}: included=${included}`, + ) + } + } + checkClientOperations( + renderedModules(chunks), + screen, + screen === 'options' ? 'invalidateQueries' : undefined, + ) + } +} + +const reactPeer = /^react(?:-dom)?(?:\/|$)/ + +function retainedExports(modules) { + return new Map( + modules.map(([id, module]) => [id, new Set(module.renderedExports)]), + ) +} + +function sizesOf(chunks) { + const sizes = { raw: 0, gzip: 0, brotli: 0 } + for (const chunk of chunks) { + const js = Buffer.from(chunk.code) + sizes.raw += js.length + sizes.gzip += gzipSync(js, { level: 9 }).length + sizes.brotli += brotliCompressSync(js, { + params: { [constants.BROTLI_PARAM_QUALITY]: 11 }, + }).length + } + return sizes +} + +async function measure(packageName, screen) { + const app = await buildApp(packageName, screen) + checkApp(app, packageName, screen) + + // Only published package JS from the appropriate checkout may enter the + // Query chunk. Keep the original app entrypoint so it drives tree-shaking. + const source = + packageName === baseline && baseCheckout ? baseCheckout : checkout + const owners = runtimeOwners(source, packageName) + const belongsToAdapter = (id) => owners.some((dir) => id.startsWith(dir)) + const attributed = await buildApp(packageName, screen, belongsToAdapter) + const library = attributed.filter((chunk) => chunk.name === 'query-runtime') + assert.equal( + library.length, + 1, + `Expected one Query chunk in ${packageName} ${screen}`, + ) + const actual = renderedModules(library) + const expected = renderedModules(app).filter(([id]) => belongsToAdapter(id)) + for (const dir of owners) { + if (!expected.some(([id]) => id.startsWith(dir))) { + throw new Error(`Missing Query runtime from ${dir} in ${screen}`) + } + } + assert.deepEqual( + retainedExports(actual), + retainedExports(expected), + `Query modules or exports differ from the production ${packageName} ${screen} app`, + ) + if ( + renderedModules(attributed.filter((chunk) => chunk !== library[0])).some( + ([id]) => belongsToAdapter(id), + ) || + [...library[0].imports, ...library[0].dynamicImports].some( + (id) => !reactPeer.test(id), + ) + ) { + throw new Error( + `Query runtime spans additional chunks in ${packageName} ${screen}`, + ) + } + const largestModules = actual + .sort(([, a], [, b]) => b.renderedLength - a.renderedLength) + .slice(0, 5) + .map(([id]) => + normalizePath(path.relative(path.join(source, 'packages'), id)), + ) + return { library: sizesOf(library), app: sizesOf(app), largestModules } +} + +// A combined app cannot tell whether each projection pulls in its sibling, +// or whether rendering a boundary pulls in paused-mutation restoration. +async function checkPluggableExports() { + const { + QueryClient, + query, + queryOptions, + mutationOptions, + infiniteQueryOptions, + QueriesObserver, + notifyManager, + } = await import(pluggable) + assert.deepEqual( + Object.getOwnPropertyNames(QueryClient.prototype), + ['constructor'], + 'QueryClient operations must be independently importable', + ) + if ( + 'getQueries' in QueriesObserver.prototype || + 'setBatchNotifyFunction' in notifyManager + ) { + throw new Error( + `${pluggable} exposed another adapter's observer or batch notification API`, + ) + } + if ( + typeof queryOptions !== 'function' || + queryOptions !== query || + queryOptions !== mutationOptions || + queryOptions !== infiniteQueryOptions + ) { + throw new Error( + `${pluggable} must use the same identity function for query and the three option factories`, + ) + } + + const expected = { + query: [], + suspenseQuery: ['suspenseQuery', 'suspense'], + infiniteQuery: [ + 'infiniteQuery', + 'infiniteQueryObserver', + 'infiniteQueryBehavior', + ], + fetchInfiniteQuery: ['fetchInfiniteQuery', 'infiniteQueryBehavior'], + QueryClient: [], + fetchQuery: [], + setQueryData: [], + getMutationCache: ['mutationCache'], + select: ['select', 'projectResult'], + placeholderData: ['placeholderData', 'projectResult'], + serialScope: ['serialScope'], + ...Object.fromEntries( + Object.keys(bulkOperations).map((name) => [name, ['cacheOperations']]), + ), + HydrationBoundary: ['infiniteQueryBehavior'], + dehydrate: [], + hydrate: [ + 'infiniteQueryBehavior', + 'mutation', + 'mutationCache', + 'serialScope', + ], + } + const features = new Set(Object.values(expected).flat()) + const entry = path.join(root, 'public-export-probe.js') + for (const [name, required] of Object.entries(expected)) { + const results = await build({ + root, + configFile: false, + logLevel: 'error', + plugins: [ + { + name: 'import-one-public-export', + resolveId(id) { + if (id === entry) return id + }, + load(id) { + if (id === entry) return `export { ${name} } from '${pluggable}'` + }, + }, + ], + build: { + write: false, + lib: { entry, formats: ['es'], fileName: 'probe' }, + rolldownOptions: { + external: ['react', 'react/jsx-runtime'], + checks: { moduleLevelDirective: false }, + }, + }, + }) + const modules = results + .flatMap(({ output }) => + output + .filter((file) => file.type === 'chunk') + .flatMap((chunk) => Object.entries(chunk.modules)), + ) + .filter(([, module]) => module.renderedLength > 0) + for (const feature of features) { + const included = modules.some(([id]) => rendersFeature(id, feature)) + if (included !== required.includes(feature)) { + throw new Error( + `Importing ${name} unexpectedly ${included ? 'included' : 'excluded'} ${feature}`, + ) + } + } + if ( + ['QueryClient', 'fetchQuery', 'setQueryData'].includes(name) || + Object.hasOwn(bulkOperations, name) + ) { + checkClientOperations( + modules, + name, + name === 'QueryClient' ? undefined : name, + ) + } + } +} +await checkPluggableExports() + +const integer = new Intl.NumberFormat('en-US') +function formatChange(bytes, baselineBytes) { + const difference = bytes - baselineBytes + const sign = difference > 0 ? '+' : '' + const percent = ((100 * difference) / baselineBytes).toFixed(2) + return `${sign}${integer.format(difference)} B (${sign}${percent}%)` +} + +function formatSize(bytes, baselineBytes, isBaseline) { + const size = `${integer.format(bytes)} B` + if (isBaseline) return size + return `${size}
${formatChange(bytes, baselineBytes)}` +} + +function revision(directory) { + return execFileSync('git', ['-C', directory, 'rev-parse', 'HEAD'], { + encoding: 'utf8', + }).trim() +} + +const head = revision(root) +const base = baseCheckout ? revision(baseCheckout) : head +const lines = [ + '## React Query bundle size', + '', + '### Gzipped Query runtime', + '', + 'Each row compares the Query JavaScript used by the same app. The change is measured against v6 for that row. Negative values mean fewer bytes.', + '', + '| Workload | React Query v6 | React Query Pluggable | Change vs v6 |', + '| --- | ---: | ---: | ---: |', +] +const results = [] +for (const { screen, title } of workloads) { + const rows = [] + for (const name of packages) { + rows.push({ name, ...(await measure(name, screen)) }) + } + results.push({ screen, title, rows }) + const [v6Gzip, pluggableGzip] = rows.map((row) => row.library.gzip) + lines.push( + `| ${title} | ${integer.format(v6Gzip)} B | ${integer.format(pluggableGzip)} B | ${formatChange(pluggableGzip, v6Gzip)} |`, + ) +} +lines.push( + '', + 'The pluggable read-only list retains the query client, cache, query and observer. Its production build drops the Suspense builder and policy, mutation cache and observer, polling scheduler, infinite-query behavior, selection, placeholder data, serial scopes and bulk cache operations. Both bookmark apps retain the mutation cache and observer.', + '', + `Baseline adapter and core at \`${base}\` (${baseCheckout ? 'base checkout' : 'current checkout'}). Pluggable adapter, core and fixture at \`${head}\`.`, +) +function addTable(key, heading, description) { + lines.push( + '', + '
', + `${heading}`, + '', + description, + '', + '| Workload | Package | Minified JS | Gzip | Brotli |', + '| --- | --- | ---: | ---: | ---: |', + ) + for (const { title, rows } of results) { + const baselineSizes = rows[0][key] + for (const row of rows) { + const cells = Object.entries(row[key]).map(([metric, value]) => + formatSize(value, baselineSizes[metric], row.name === baseline), + ) + lines.push(`| ${title} | \`${row.name}\` | ${cells.join(' | ')} |`) + } + } + if (key === 'library') { + const readOnly = results + .find(({ screen }) => screen === 'query') + .rows.find(({ name }) => name === pluggable) + lines.push( + '', + `Largest modules in the read-only pluggable chunk, by rendered size before minification: ${readOnly.largestModules.map((name) => `\`${name}\``).join(', ')}.`, + ) + } + lines.push('', '
') +} +addTable( + 'library', + 'Query runtime sizes · minified JS, gzip and Brotli', + 'The app entry drives tree-shaking. This build externalizes React and React DOM and groups the adapter and its retained query-core modules into one ESM chunk for each package. Each cell measures the isolated chunk directly.', +) +addTable( + 'app', + 'Whole production app sizes · minified JS, gzip and Brotli', + 'Each build includes the app, React, React DOM and Query. This measures the JavaScript delivered to the browser.', +) +lines.push( + '', + 'All sizes are bytes. Each JavaScript chunk is compressed separately with gzip level 9 and Brotli quality 11, then summed.', + '', +) +const report = lines.join('\n') +await writeFile(path.join(root, 'dist/report.md'), report) +process.stdout.write(report) diff --git a/integrations/react/bundle-size/package.json b/integrations/react/bundle-size/package.json new file mode 100644 index 00000000000..f1fa4a16bac --- /dev/null +++ b/integrations/react/bundle-size/package.json @@ -0,0 +1,25 @@ +{ + "name": "@tanstack/query-integration-react-bundle-size", + "private": true, + "type": "module", + "scripts": { + "measure": "node measure.mjs", + "test:browser": "vitest run --config vitest.browser.config.js", + "test:browser:ui": "vitest --watch --ui --config vitest.browser.config.js", + "browser:install": "playwright install --with-deps --only-shell chromium" + }, + "dependencies": { + "@tanstack/react-query": "workspace:*", + "@tanstack/react-query-pluggable": "workspace:*", + "react": "catalog:", + "react-dom": "catalog:" + }, + "devDependencies": { + "@vitest/browser-playwright": "5.0.5", + "@vitest/ui": "5.0.5", + "playwright": "1.65.1", + "rollup-plugin-visualizer": "7.1.1", + "vite": "^8.3.8", + "vitest": "^5.0.5" + } +} diff --git a/integrations/react/bundle-size/public/books-1.json b/integrations/react/bundle-size/public/books-1.json new file mode 100644 index 00000000000..e64ec490101 --- /dev/null +++ b/integrations/react/bundle-size/public/books-1.json @@ -0,0 +1 @@ +{ "titles": ["Middlemarch", "Persuasion"], "next": 2 } diff --git a/integrations/react/bundle-size/public/books-2.json b/integrations/react/bundle-size/public/books-2.json new file mode 100644 index 00000000000..c58cb48908a --- /dev/null +++ b/integrations/react/bundle-size/public/books-2.json @@ -0,0 +1 @@ +{ "titles": ["Villette", "North and South"], "next": null } diff --git a/integrations/react/bundle-size/src/books.js b/integrations/react/bundle-size/src/books.js new file mode 100644 index 00000000000..d15211e5647 --- /dev/null +++ b/integrations/react/bundle-size/src/books.js @@ -0,0 +1,5 @@ +export async function fetchBooks(page, signal) { + const response = await fetch(`./books-${page}.json`, { signal }) + if (!response.ok) throw new Error(`Could not load page ${page}`) + return response.json() +} diff --git a/integrations/react/bundle-size/src/main.jsx b/integrations/react/bundle-size/src/main.jsx new file mode 100644 index 00000000000..244628c2b3b --- /dev/null +++ b/integrations/react/bundle-size/src/main.jsx @@ -0,0 +1,13 @@ +import * as React from 'react' +import { createRoot } from 'react-dom/client' +import { QueryClient, QueryClientProvider } from '#adapter' +import { ReadingList } from '#screen' + +const client = new QueryClient() + +createRoot(document.getElementById('root')).render( + +

Reading list

+ +
, +) diff --git a/integrations/react/bundle-size/src/numeric-interval.js b/integrations/react/bundle-size/src/numeric-interval.js new file mode 100644 index 00000000000..b22ad6afd12 --- /dev/null +++ b/integrations/react/bundle-size/src/numeric-interval.js @@ -0,0 +1 @@ +export const interval = 250 diff --git a/integrations/react/bundle-size/src/options.jsx b/integrations/react/bundle-size/src/options.jsx new file mode 100644 index 00000000000..b220a3ddb5a --- /dev/null +++ b/integrations/react/bundle-size/src/options.jsx @@ -0,0 +1,67 @@ +import * as React from 'react' +import { useMutation, useQuery, useQueryClient } from '#adapter' +import { + bookmarkScope, + previousPage, + refreshBookmarks, + selectTitles, +} from '#feature-options' +import { fetchBooks } from './books.js' + +function savedBooks() { + return JSON.parse(localStorage.getItem('bookmarks') ?? '[]') +} + +export function ReadingList() { + const client = useQueryClient() + const [page, setPage] = React.useState(1) + const [events, setEvents] = React.useState([]) + const books = useQuery({ + queryKey: ['books', page], + queryFn: ({ signal }) => fetchBooks(page, signal), + select: selectTitles, + placeholderData: previousPage, + }) + const saved = useQuery({ queryKey: ['bookmarks'], queryFn: savedBooks }) + const bookmark = useMutation({ + scope: bookmarkScope, + mutationFn: async (title) => { + setEvents((items) => [...items, `Saving ${title}`]) + await Promise.resolve() + localStorage.setItem( + 'bookmarks', + JSON.stringify([...savedBooks(), title]), + ) + setEvents((items) => [...items, `Saved ${title}`]) + }, + onSuccess: () => refreshBookmarks(client), + }) + if (books.isPending) return

Loading books…

+ if (books.isError) return

{books.error.message}

+ return ( + <> +
    + {books.data.map((title) => ( +
  • {title}
  • + ))} +
+ {books.isPlaceholderData && ( +

Showing the previous page

+ )} + + +

Bookmarks: {saved.data?.join(', ')}

+
    + {events.map((event, index) => ( +
  1. {event}
  2. + ))} +
+ + ) +} diff --git a/integrations/react/bundle-size/src/paginated.jsx b/integrations/react/bundle-size/src/paginated.jsx new file mode 100644 index 00000000000..d545d72eee3 --- /dev/null +++ b/integrations/react/bundle-size/src/paginated.jsx @@ -0,0 +1,59 @@ +import * as React from 'react' +import { + queryOptions, + infiniteQueryOptions, + mutationOptions, + useMutation, + useQuery, +} from '#adapter' +import { useBookPages } from '#query-hooks' +import { fetchBooks } from './books.js' + +export function ReadingList() { + const books = useBookPages( + infiniteQueryOptions({ + queryKey: ['books'], + queryFn: ({ pageParam, signal }) => fetchBooks(pageParam, signal), + initialPageParam: 1, + getNextPageParam: (lastPage) => lastPage.next, + }), + ) + const bookmark = useQuery( + queryOptions({ + queryKey: ['bookmark'], + queryFn: () => localStorage.getItem('bookmark'), + }), + ) + const save = useMutation( + mutationOptions({ + mutationFn: async (title) => localStorage.setItem('bookmark', title), + onSuccess: () => bookmark.refetch(), + }), + ) + if (books.isPending) return

Loading books…

+ if (books.isError) return

{books.error.message}

+ return ( + <> + {bookmark.data &&

Bookmarked: {bookmark.data}

} +
    + {books.data.pages + .flatMap((page) => page.titles) + .map((title) => ( +
  • + {title}{' '} + +
  • + ))} +
+ {books.hasNextPage && ( + + )} + {save.isError &&

{save.error.message}

} + + ) +} diff --git a/integrations/react/bundle-size/src/pluggable-interval.js b/integrations/react/bundle-size/src/pluggable-interval.js new file mode 100644 index 00000000000..ca450d5790b --- /dev/null +++ b/integrations/react/bundle-size/src/pluggable-interval.js @@ -0,0 +1,3 @@ +import { refetchInterval } from '#adapter' + +export const interval = refetchInterval(250) diff --git a/integrations/react/bundle-size/src/pluggable-options.js b/integrations/react/bundle-size/src/pluggable-options.js new file mode 100644 index 00000000000..62d8cb520fb --- /dev/null +++ b/integrations/react/bundle-size/src/pluggable-options.js @@ -0,0 +1,12 @@ +import { + invalidateQueries, + placeholderData, + select, + serialScope, +} from '#adapter' + +export const selectTitles = select((page) => page.titles) +export const previousPage = placeholderData((previous) => previous) +export const bookmarkScope = serialScope('bookmarks') +export const refreshBookmarks = (client) => + invalidateQueries(client, { queryKey: ['bookmarks'] }) diff --git a/integrations/react/bundle-size/src/pluggable-query.js b/integrations/react/bundle-size/src/pluggable-query.js new file mode 100644 index 00000000000..ab789642baa --- /dev/null +++ b/integrations/react/bundle-size/src/pluggable-query.js @@ -0,0 +1,17 @@ +import { infiniteQuery, query, suspenseQuery, useQuery } from '#adapter' + +export function useBookQuery(options) { + return useQuery(query(options)) +} + +export function useSuspenseBookQuery(options) { + return useQuery(suspenseQuery(options)) +} + +export function useBookPages(options) { + return useQuery(infiniteQuery(options)) +} + +export function useSuspenseBookPages(options) { + return useQuery(suspenseQuery(infiniteQuery(options))) +} diff --git a/integrations/react/bundle-size/src/polling.jsx b/integrations/react/bundle-size/src/polling.jsx new file mode 100644 index 00000000000..05fdae7e6bf --- /dev/null +++ b/integrations/react/bundle-size/src/polling.jsx @@ -0,0 +1,76 @@ +import * as React from 'react' +import { interval } from '#polling-option' +import { + useBookPages, + useBookQuery, + useSuspenseBookPages, + useSuspenseBookQuery, +} from '#query-hooks' +import { fetchBooks } from './books.js' + +function options(name) { + return { + queryKey: ['books', name], + queryFn: ({ pageParam = 1, signal }) => fetchBooks(pageParam, signal), + refetchInterval: interval, + refetchIntervalInBackground: true, + } +} + +const pagination = { + initialPageParam: 1, + getNextPageParam: (page) => page.next, +} + +function BookRow({ label, result, page }) { + return ( +
  • + {label}: {page?.titles.join(', ')}{' '} + {result.dataUpdatedAt > 0 && ( + + )} +
  • + ) +} + +function SuspenseBook() { + const result = useSuspenseBookQuery(options('suspense')) + return +} + +function SuspensePages() { + const result = useSuspenseBookPages({ + ...options('suspense-infinite'), + ...pagination, + }) + return ( + + ) +} + +export function ReadingList() { + const query = useBookQuery(options('query')) + const infinite = useBookPages({ ...options('infinite'), ...pagination }) + return ( +
      + + + Loading suspense query…}> + + + Loading suspense pages…}> + + +
    + ) +} diff --git a/integrations/react/bundle-size/src/query.jsx b/integrations/react/bundle-size/src/query.jsx new file mode 100644 index 00000000000..51ae3ccbe3e --- /dev/null +++ b/integrations/react/bundle-size/src/query.jsx @@ -0,0 +1,19 @@ +import * as React from 'react' +import { useBookQuery } from '#query-hooks' +import { fetchBooks } from './books.js' + +export function ReadingList() { + const books = useBookQuery({ + queryKey: ['books', 1], + queryFn: ({ signal }) => fetchBooks(1, signal), + }) + if (books.isPending) return

    Loading books…

    + if (books.isError) return

    {books.error.message}

    + return ( +
      + {books.data.titles.map((title) => ( +
    • {title}
    • + ))} +
    + ) +} diff --git a/integrations/react/bundle-size/src/v6-options.js b/integrations/react/bundle-size/src/v6-options.js new file mode 100644 index 00000000000..b6f20e37c43 --- /dev/null +++ b/integrations/react/bundle-size/src/v6-options.js @@ -0,0 +1,5 @@ +export const selectTitles = (page) => page.titles +export const previousPage = (previous) => previous +export const bookmarkScope = { id: 'bookmarks' } +export const refreshBookmarks = (client) => + client.invalidateQueries({ queryKey: ['bookmarks'] }) diff --git a/integrations/react/bundle-size/src/v6-query.js b/integrations/react/bundle-size/src/v6-query.js new file mode 100644 index 00000000000..17ebd6494d6 --- /dev/null +++ b/integrations/react/bundle-size/src/v6-query.js @@ -0,0 +1,6 @@ +export { + useInfiniteQuery as useBookPages, + useQuery as useBookQuery, + useSuspenseInfiniteQuery as useSuspenseBookPages, + useSuspenseQuery as useSuspenseBookQuery, +} from '#adapter' diff --git a/integrations/react/bundle-size/vitest.browser.config.js b/integrations/react/bundle-size/vitest.browser.config.js new file mode 100644 index 00000000000..07f125f521f --- /dev/null +++ b/integrations/react/bundle-size/vitest.browser.config.js @@ -0,0 +1,50 @@ +import { playwright } from '@vitest/browser-playwright' +import { defineConfig } from 'vitest/config' + +const pendingBooks = new Map() +const booksUrl = (adapter) => `/polling/${adapter}/books-1.json` + +export default defineConfig({ + root: import.meta.dirname, + // Serve the measured apps from disk, including their production JS chunks. + publicDir: 'dist', + plugins: [ + { + name: 'hold-polling-fixtures', + configureServer(server) { + server.middlewares.use((request, response, next) => { + const gate = pendingBooks.get(request.url) + if (gate) { + gate.requested.resolve() + gate.response.promise.then(() => next(), next) + } else next() + }) + }, + }, + ], + test: { + include: ['browser/*.test.js'], + browser: { + enabled: true, + headless: true, + provider: playwright(), + instances: [{ browser: 'chromium' }], + commands: { + holdPollingBooks(_, adapter) { + pendingBooks.set(booksUrl(adapter), { + requested: Promise.withResolvers(), + response: Promise.withResolvers(), + }) + }, + waitForPollingRequest(_, adapter) { + return pendingBooks.get(booksUrl(adapter)).requested.promise + }, + releasePollingBooks(_, adapter) { + const url = booksUrl(adapter) + pendingBooks.get(url).response.resolve() + pendingBooks.delete(url) + }, + }, + }, + }, +}) diff --git a/integrations/react/nodenext/README.md b/integrations/react/nodenext/README.md index 0cbec8b73d7..8cc19458b58 100644 --- a/integrations/react/nodenext/README.md +++ b/integrations/react/nodenext/README.md @@ -6,6 +6,7 @@ Checks that `@tanstack/react-query` resolves and emits declarations under `modul - `src/hooks.ts` (ESM, since `package.json` sets `"type": "module"`) exports a hook that calls `useQuery`. - `tsconfig.json` sets `module` and `moduleResolution` to `nodenext` with `declaration` and `emitDeclarationOnly`, so TypeScript writes declarations to `dist/`. +- `src/sharedTypes.ts` augments `@tanstack/query-core`’s `Register` and passes a pluggable-tagged query key to the core and pluggable clients to check inference across the published ESM entry points. - The check runs with TypeScript 6, TypeScript 7.0, and TypeScript 7.1 (dev build) from the root `node_modules`. - CI runs the `test:types` script, which runs `test:types:ts6`, `test:types:ts7`, and `test:types:ts71`. diff --git a/integrations/react/nodenext/package.json b/integrations/react/nodenext/package.json index c587035a285..2b1b1eea17a 100644 --- a/integrations/react/nodenext/package.json +++ b/integrations/react/nodenext/package.json @@ -9,7 +9,9 @@ "test:types:ts71": "node ../../../node_modules/typescript71/lib/tsc.js --pretty false --project tsconfig.json" }, "dependencies": { - "@tanstack/react-query": "workspace:*" + "@tanstack/query-core": "workspace:*", + "@tanstack/react-query": "workspace:*", + "@tanstack/react-query-pluggable": "workspace:*" }, "devDependencies": { "@types/react": "^19.3.0" diff --git a/integrations/react/nodenext/src/sharedTypes.ts b/integrations/react/nodenext/src/sharedTypes.ts new file mode 100644 index 00000000000..6794c49c352 --- /dev/null +++ b/integrations/react/nodenext/src/sharedTypes.ts @@ -0,0 +1,35 @@ +import { QueryClient as CoreClient } from '@tanstack/query-core' +import { + QueryClient, + getQueryData, + queryOptions, +} from '@tanstack/react-query-pluggable' +import type { QueryMeta as CoreMeta } from '@tanstack/query-core' +import type { QueryMeta as PluggableMeta } from '@tanstack/react-query-pluggable' + +type BookMeta = { shelf: string } + +declare module '@tanstack/query-core' { + interface Register { + queryMeta: BookMeta + } +} + +type Assert = Matches +type Same = [A, B] extends [B, A] ? true : false + +export type SharedMetadata = [ + Assert>, + Assert>, +] + +const book = queryOptions({ queryKey: ['book'], queryFn: () => 'Dune' }) + +// Both clients infer the data type from the adapter's tagged key. +export const fromCore: string | undefined = new CoreClient().getQueryData( + book.queryKey, +) +export const fromPluggable: string | undefined = getQueryData( + new QueryClient(), + book.queryKey, +) diff --git a/knip.config.ts b/knip.config.ts index 802c9b9a485..26a6fada2d3 100644 --- a/knip.config.ts +++ b/knip.config.ts @@ -1,6 +1,7 @@ import reactQueryDevtools from './packages/react-query-devtools/package.json' import reactQueryNextExperimental from './packages/react-query-next-experimental/package.json' import reactQueryPersistClient from './packages/react-query-persist-client/package.json' +import reactQueryPluggable from './packages/react-query-pluggable/package.json' import reactQuery from './packages/react-query/package.json' import type { KnipConfig } from 'knip' @@ -41,6 +42,15 @@ export default { 'packages/react-query': { ignoreDependencies: optionalPeerDependencies(reactQuery), }, + 'packages/react-query-pluggable': { + // These internal imports are exercised by the upstream compatibility suites. + entry: [ + 'src/suspense.ts', + 'src/runtime/{query,notifyManager,utils}.ts', + 'tests/compat-*.ts', + ], + ignoreDependencies: optionalPeerDependencies(reactQueryPluggable), + }, 'packages/react-query-devtools': { ignoreDependencies: optionalPeerDependencies(reactQueryDevtools), }, diff --git a/nx.json b/nx.json index 84ef0aa852b..2733e7562d5 100644 --- a/nx.json +++ b/nx.json @@ -24,6 +24,19 @@ "!{projectRoot}/tests/**/*", "!{projectRoot}/eslint.config.js", "!{projectRoot}/oxlint.config.ts" + ], + "reactQueryCompatibility": [ + "{workspaceRoot}/scripts/test-react-query-compat.mjs", + "{workspaceRoot}/scripts/port-query-client-tests.mjs", + "{workspaceRoot}/scripts/port-query-projection-tests.mjs", + "{workspaceRoot}/scripts/react-query-compat.config.ts", + "{workspaceRoot}/packages/query-core/src/__tests__/**/*", + "{workspaceRoot}/packages/query-core/vite.config.ts", + "{workspaceRoot}/packages/react-query/src/__tests__/**/*", + "{workspaceRoot}/packages/react-query/test-setup.ts", + "{workspaceRoot}/packages/react-query/vite.config.ts", + "{workspaceRoot}/packages/query-persist-client-core/src/**/*", + "{workspaceRoot}/packages/query-test-utils/src/**/*" ] }, "targetDefaults": { diff --git a/packages/query-core/package.json b/packages/query-core/package.json index b0667e0cf84..8ca2510d094 100644 --- a/packages/query-core/package.json +++ b/packages/query-core/package.json @@ -40,6 +40,11 @@ "types": "./build/index.d.ts", "default": "./build/index.js" }, + "./primitives": { + "@tanstack/custom-condition": "./src/primitives.ts", + "types": "./build/primitives.d.ts", + "default": "./build/primitives.js" + }, "./package.json": "./package.json" }, "sideEffects": false, diff --git a/packages/query-core/src/__tests__/frameworkAdapters/frameworkAdapters.test-d.ts b/packages/query-core/src/__tests__/frameworkAdapters/frameworkAdapters.test-d.ts new file mode 100644 index 00000000000..9ec03113f45 --- /dev/null +++ b/packages/query-core/src/__tests__/frameworkAdapters/frameworkAdapters.test-d.ts @@ -0,0 +1,43 @@ +import { describe, expectTypeOf, it } from 'vitest' +import { QueriesObserver, QueryClient } from '../..' +import { createNotifyManager } from '../../notifyManager' +import type { Query } from '../..' + +describe('framework adapter APIs', () => { + it('should only expose its documented members', () => { + expectTypeOf>().toEqualTypeOf< + | 'batch' + | 'batchCalls' + | 'schedule' + | 'setNotifyFunction' + | 'setBatchNotifyFunction' + | 'setScheduler' + >() + }) + + describe('setBatchNotifyFunction', () => { + it('should only accept a function taking a callback', () => { + const localNotifyManager = createNotifyManager() + + expectTypeOf( + localNotifyManager.setBatchNotifyFunction, + ).parameters.toEqualTypeOf<[fn: (callback: () => void) => void]>() + }) + + it('should return void', () => { + const localNotifyManager = createNotifyManager() + + expectTypeOf( + localNotifyManager.setBatchNotifyFunction, + ).returns.toEqualTypeOf() + }) + }) + + describe('getQueries', () => { + it('should return the observed queries', () => { + const observer = new QueriesObserver(new QueryClient(), []) + + expectTypeOf(observer.getQueries()).toEqualTypeOf>() + }) + }) +}) diff --git a/packages/query-core/src/__tests__/frameworkAdapters/frameworkAdapters.test.ts b/packages/query-core/src/__tests__/frameworkAdapters/frameworkAdapters.test.ts new file mode 100644 index 00000000000..9deeec16882 --- /dev/null +++ b/packages/query-core/src/__tests__/frameworkAdapters/frameworkAdapters.test.ts @@ -0,0 +1,48 @@ +import { createKey } from '@tanstack/query-test-utils' +import { describe, expect, it, vi } from 'vitest' +import { QueriesObserver, QueryClient } from '../..' +import { createNotifyManager } from '../../notifyManager' + +describe('framework adapter APIs', () => { + it('should use custom batch notify function', async () => { + const notifyManagerTest = createNotifyManager() + const batchNotifySpy = vi.fn<(callback: () => void) => void>((cb) => cb()) + const callbackSpy1 = vi.fn<() => void>() + const callbackSpy2 = vi.fn<() => void>() + + notifyManagerTest.setBatchNotifyFunction(batchNotifySpy) + + notifyManagerTest.batch(() => { + notifyManagerTest.schedule(callbackSpy1) + notifyManagerTest.schedule(callbackSpy2) + }) + + await Promise.resolve() + expect(batchNotifySpy).toHaveBeenCalledWith(expect.any(Function)) + expect(callbackSpy1).toHaveBeenCalledWith() + expect(callbackSpy2).toHaveBeenCalledWith() + }) + + it('should return current queries via getQueries', async () => { + const queryClient = new QueryClient() + const key1 = createKey() + const key2 = createKey() + const queryFn1 = vi.fn<() => number>().mockReturnValue(1) + const queryFn2 = vi.fn<() => number>().mockReturnValue(2) + const observer = new QueriesObserver(queryClient, [ + { queryKey: key1, queryFn: queryFn1 }, + { queryKey: key2, queryFn: queryFn2 }, + ]) + const unsubscribe = observer.subscribe(() => undefined) + await Promise.resolve() + + const queries = observer.getQueries() + + expect(queries).toHaveLength(2) + expect(queries[0]?.queryKey).toStrictEqual(key1) + expect(queries[1]?.queryKey).toStrictEqual(key2) + + unsubscribe() + queryClient.clear() + }) +}) diff --git a/packages/query-core/src/__tests__/hydration.test.tsx b/packages/query-core/src/__tests__/hydration.test.tsx index 716926661dd..c60ce08910f 100644 --- a/packages/query-core/src/__tests__/hydration.test.tsx +++ b/packages/query-core/src/__tests__/hydration.test.tsx @@ -1,4 +1,5 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { serialScope } from '@tanstack/query-test-utils/scope' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { dehydrate, hydrate } from '../hydration' import { dehydrateQuery } from '../index' @@ -978,9 +979,7 @@ describe('dehydration and rehydration', () => { mutationFn: () => { return Promise.resolve('mutation') }, - scope: { - id: 'scope', - }, + scope: serialScope('scope'), }, 'vars', ) diff --git a/packages/query-core/src/__tests__/infiniteFetch.ts b/packages/query-core/src/__tests__/infiniteFetch.ts new file mode 100644 index 00000000000..2e645408197 --- /dev/null +++ b/packages/query-core/src/__tests__/infiniteFetch.ts @@ -0,0 +1,13 @@ +import { infiniteQueryBehavior } from '../infiniteQueryBehavior' + +export function prepareInfiniteFetch( + ...args: Parameters< + ReturnType< + typeof infiniteQueryBehavior + >['onFetch'] + > +) { + infiniteQueryBehavior().onFetch( + ...args, + ) +} diff --git a/packages/query-core/src/__tests__/infiniteQueryBehavior.test.tsx b/packages/query-core/src/__tests__/infiniteQueryBehavior.test.tsx index 4549e7ecb5e..d00e81ae014 100644 --- a/packages/query-core/src/__tests__/infiniteQueryBehavior.test.tsx +++ b/packages/query-core/src/__tests__/infiniteQueryBehavior.test.tsx @@ -6,7 +6,7 @@ import { QueryClient, defaultQueryFn, } from '..' -import { infiniteQueryBehavior } from '../infiniteQueryBehavior' +import { prepareInfiniteFetch } from './infiniteFetch' import type { InfiniteData, InfiniteQueryObserverResult, @@ -351,7 +351,6 @@ describe('InfiniteQueryBehavior', () => { return pageParam }) - const behavior = infiniteQueryBehavior() const context = { client: queryClient, queryKey: key, @@ -372,7 +371,10 @@ describe('InfiniteQueryBehavior', () => { signal: abortController.signal, } - behavior.onFetch(context as any, {} as any) + prepareInfiniteFetch( + context as any, + {} as any, + ) await expect(context.fetchFn()).rejects.toBe(abortController.signal.reason) expect(queryFn).toHaveBeenCalledTimes(1) diff --git a/packages/query-core/src/__tests__/infiniteQueryObserver.test-d.tsx b/packages/query-core/src/__tests__/infiniteQueryObserver.test-d.tsx index 584ba64a256..427dbc2401c 100644 --- a/packages/query-core/src/__tests__/infiniteQueryObserver.test-d.tsx +++ b/packages/query-core/src/__tests__/infiniteQueryObserver.test-d.tsx @@ -1,4 +1,8 @@ import { createKey } from '@tanstack/query-test-utils' +import { + projectionInput, + selectOption, +} from '@tanstack/query-test-utils/projection' import { afterEach, beforeEach, describe, expectTypeOf, it } from 'vitest' import { InfiniteQueryObserver, QueryClient } from '..' import type { @@ -298,7 +302,7 @@ describe('infiniteQueryObserver', () => { queryFn: () => Promise.resolve({ value: 'data' }), initialPageParam: 1, getNextPageParam: () => 1, - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toEqualTypeOf< InfiniteData<{ value: string }, number> >() @@ -313,7 +317,7 @@ describe('infiniteQueryObserver', () => { queryFn: () => Promise.resolve({ count: 1 }), initialPageParam: 1, getNextPageParam: () => 1, - select: (data) => data.pages.length, + [selectOption]: (data) => data.pages.length, }) expectTypeOf(observer.getCurrentResult().data).toEqualTypeOf< @@ -951,7 +955,7 @@ describe('infiniteQueryObserver', () => { queryFn: () => Promise.resolve({ value: 'data' }), initialPageParam: 1, getNextPageParam: () => 1, - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toEqualTypeOf< InfiniteData<{ value: string }, number> >() @@ -1004,7 +1008,7 @@ describe('infiniteQueryObserver', () => { getNextPageParam: () => 1, }) - expectTypeOf(observer.options.select).toEqualTypeOf< + expectTypeOf(projectionInput(observer.options.select)).toEqualTypeOf< | (( data: InfiniteData<{ value: string }, number>, ) => InfiniteData<{ value: string }, unknown>) diff --git a/packages/query-core/src/__tests__/infiniteQueryObserver.test.tsx b/packages/query-core/src/__tests__/infiniteQueryObserver.test.tsx index 4deb4606da7..2b1def6188b 100644 --- a/packages/query-core/src/__tests__/infiniteQueryObserver.test.tsx +++ b/packages/query-core/src/__tests__/infiniteQueryObserver.test.tsx @@ -1,10 +1,10 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { selectOption } from '@tanstack/query-test-utils/projection' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { InfiniteQueryObserver, QueryClient } from '..' +import type { GetNextPageParamFunction, GetPreviousPageParamFunction } from '..' import type { DefaultedInfiniteQueryObserverOptions, - GetNextPageParamFunction, - GetPreviousPageParamFunction, InfiniteData, } from '../types' @@ -27,7 +27,7 @@ describe('InfiniteQueryObserver', () => { const observer = new InfiniteQueryObserver(queryClient, { queryKey: key, queryFn: () => sleep(10).then(() => 1), - select: (data) => ({ + [selectOption]: (data) => ({ pages: data.pages.map((x) => `${x}`), pageParams: data.pageParams, }), @@ -56,7 +56,7 @@ describe('InfiniteQueryObserver', () => { meta, queryKey: key, queryFn, - select: (data) => ({ + [selectOption]: (data) => ({ pages: data.pages.map((x) => `${x}`), pageParams: data.pageParams, }), diff --git a/packages/query-core/src/__tests__/mutation.test-d.tsx b/packages/query-core/src/__tests__/mutation.test-d.tsx index e2e692e6269..831f84590db 100644 --- a/packages/query-core/src/__tests__/mutation.test-d.tsx +++ b/packages/query-core/src/__tests__/mutation.test-d.tsx @@ -1,6 +1,7 @@ import { describe, expectTypeOf, it } from 'vitest' import { Mutation } from '../mutation' import { QueryClient } from '../queryClient' +import type { serialScope } from '@tanstack/query-test-utils/scope' import type { Action, MutationState } from '../mutation' import type { MutationObserver } from '../mutationObserver' import type { @@ -490,7 +491,7 @@ describe('mutation', () => { describe('scope', () => { it('should be an optional scope carrying a string id', () => { expectTypeOf().toEqualTypeOf< - { id: string } | undefined + ReturnType | undefined >() }) }) diff --git a/packages/query-core/src/__tests__/mutation.test.tsx b/packages/query-core/src/__tests__/mutation.test.tsx index fd98e764e32..aab835a7da0 100644 --- a/packages/query-core/src/__tests__/mutation.test.tsx +++ b/packages/query-core/src/__tests__/mutation.test.tsx @@ -1,4 +1,5 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { serialScope } from '@tanstack/query-test-utils/scope' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { MutationCache, QueryClient, focusManager, onlineManager } from '..' import { Mutation } from '../mutation' @@ -524,9 +525,7 @@ describe('mutation', () => { queryClient, { mutationKey: key1, - scope: { - id: 'scope', - }, + scope: serialScope('scope'), mutationFn: async () => { results.push('start-A') await sleep(10) @@ -547,9 +546,7 @@ describe('mutation', () => { queryClient, { mutationKey: key2, - scope: { - id: 'scope', - }, + scope: serialScope('scope'), mutationFn: async () => { results.push('start-B') await sleep(10) @@ -587,9 +584,7 @@ describe('mutation', () => { queryClient, { mutationKey: key1, - scope: { - id: 'scope', - }, + scope: serialScope('scope'), networkMode: 'always', mutationFn: async () => { results.push('start-A') @@ -605,9 +600,7 @@ describe('mutation', () => { queryClient, { mutationKey: key2, - scope: { - id: 'scope', - }, + scope: serialScope('scope'), networkMode: 'always', mutationFn: async () => { results.push('start-B') @@ -648,9 +641,7 @@ describe('mutation', () => { queryClient, { mutationKey: key1, - scope: { - id: 'scope', - }, + scope: serialScope('scope'), mutationFn: async () => { results.push('start-A') await sleep(10) @@ -665,9 +656,7 @@ describe('mutation', () => { queryClient, { mutationKey: key2, - scope: { - id: 'scope', - }, + scope: serialScope('scope'), mutationFn: async () => { results.push('start-B') await sleep(10) @@ -716,9 +705,7 @@ describe('mutation', () => { queryClient, { mutationKey: key1, - scope: { - id: 'scope', - }, + scope: serialScope('scope'), mutationFn: async () => { results.push('start-A') await sleep(10) @@ -733,9 +720,7 @@ describe('mutation', () => { queryClient, { mutationKey: key2, - scope: { - id: 'scope', - }, + scope: serialScope('scope'), mutationFn: async () => { results.push('start-B') await sleep(10) @@ -781,9 +766,7 @@ describe('mutation', () => { executeMutation( queryClient, { - scope: { - id: 'scope', - }, + scope: serialScope('scope'), mutationFn: () => sleep(20).then(() => 'a'), }, 'vars1', @@ -791,9 +774,7 @@ describe('mutation', () => { executeMutation( queryClient, { - scope: { - id: 'scope', - }, + scope: serialScope('scope'), onMutate: () => sleep(10), mutationFn: () => sleep(10).then(() => 'b'), }, @@ -892,9 +873,7 @@ describe('mutation', () => { executeMutation( queryClient, { - scope: { - id: '1', - }, + scope: serialScope('1'), mutationFn: async () => { results.push('start-A1') await sleep(10) @@ -908,9 +887,7 @@ describe('mutation', () => { executeMutation( queryClient, { - scope: { - id: '1', - }, + scope: serialScope('1'), mutationFn: async () => { results.push('start-B1') await sleep(10) @@ -924,9 +901,7 @@ describe('mutation', () => { executeMutation( queryClient, { - scope: { - id: '2', - }, + scope: serialScope('2'), mutationFn: async () => { results.push('start-A2') await sleep(10) @@ -940,9 +915,7 @@ describe('mutation', () => { executeMutation( queryClient, { - scope: { - id: '2', - }, + scope: serialScope('2'), mutationFn: async () => { results.push('start-B2') await sleep(10) diff --git a/packages/query-core/src/__tests__/mutationCache.test.tsx b/packages/query-core/src/__tests__/mutationCache.test.tsx index 97f076e7f86..3e422fa3e61 100644 --- a/packages/query-core/src/__tests__/mutationCache.test.tsx +++ b/packages/query-core/src/__tests__/mutationCache.test.tsx @@ -1,4 +1,5 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { serialScope } from '@tanstack/query-test-utils/scope' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { MutationCache, MutationObserver, QueryClient } from '..' import { Mutation } from '../mutation' @@ -618,11 +619,11 @@ describe('mutationCache', () => { const testClient = new QueryClient({ mutationCache: testCache }) const mutation1 = Mutation.build(testClient, { - scope: { id: 'scope1' }, + scope: serialScope('scope1'), mutationFn: () => Promise.resolve('data1'), }) const mutation2 = Mutation.build(testClient, { - scope: { id: 'scope1' }, + scope: serialScope('scope1'), mutationFn: () => Promise.resolve('data2'), }) @@ -639,7 +640,7 @@ describe('mutationCache', () => { const testClient = new QueryClient({ mutationCache: testCache }) const mutation = Mutation.build(testClient, { - scope: { id: 'scope1' }, + scope: serialScope('scope1'), mutationFn: () => Promise.resolve('data'), }) diff --git a/packages/query-core/src/__tests__/notifyManager.test-d.tsx b/packages/query-core/src/__tests__/notifyManager.test-d.tsx index 5ccfd3addcc..33a685ab1d4 100644 --- a/packages/query-core/src/__tests__/notifyManager.test-d.tsx +++ b/packages/query-core/src/__tests__/notifyManager.test-d.tsx @@ -20,17 +20,6 @@ describe('notifyManager', () => { }>() }) - it('should only expose its documented members', () => { - expectTypeOf>().toEqualTypeOf< - | 'batch' - | 'batchCalls' - | 'schedule' - | 'setNotifyFunction' - | 'setBatchNotifyFunction' - | 'setScheduler' - >() - }) - describe('batch', () => { it('should pass the return type of the callback through', () => { const localNotifyManager = createNotifyManager() @@ -161,24 +150,6 @@ describe('notifyManager', () => { }) }) - describe('setBatchNotifyFunction', () => { - it('should only accept a function taking a callback', () => { - const localNotifyManager = createNotifyManager() - - expectTypeOf( - localNotifyManager.setBatchNotifyFunction, - ).parameters.toEqualTypeOf<[fn: (callback: () => void) => void]>() - }) - - it('should return void', () => { - const localNotifyManager = createNotifyManager() - - expectTypeOf( - localNotifyManager.setBatchNotifyFunction, - ).returns.toEqualTypeOf() - }) - }) - describe('setScheduler', () => { it('should only accept a function taking a callback', () => { const localNotifyManager = createNotifyManager() diff --git a/packages/query-core/src/__tests__/notifyManager.test.tsx b/packages/query-core/src/__tests__/notifyManager.test.tsx index 46037beacee..816dc4bd975 100644 --- a/packages/query-core/src/__tests__/notifyManager.test.tsx +++ b/packages/query-core/src/__tests__/notifyManager.test.tsx @@ -76,25 +76,6 @@ describe('notifyManager', () => { expect(notifySpy).toHaveBeenCalledTimes(1) }) - it('should use custom batch notify function', async () => { - const notifyManagerTest = createNotifyManager() - const batchNotifySpy = vi.fn<(callback: () => void) => void>((cb) => cb()) - const callbackSpy1 = vi.fn<() => void>() - const callbackSpy2 = vi.fn<() => void>() - - notifyManagerTest.setBatchNotifyFunction(batchNotifySpy) - - notifyManagerTest.batch(() => { - notifyManagerTest.schedule(callbackSpy1) - notifyManagerTest.schedule(callbackSpy2) - }) - - await vi.advanceTimersByTimeAsync(0) - expect(batchNotifySpy).toHaveBeenCalledWith(expect.any(Function)) - expect(callbackSpy1).toHaveBeenCalledWith() - expect(callbackSpy2).toHaveBeenCalledWith() - }) - it('should batch calls correctly', async () => { const notifyManagerTest = createNotifyManager() const callbackSpy = vi.fn<(a: number, b: string) => void>() diff --git a/packages/query-core/src/__tests__/queriesObserver.test-d.tsx b/packages/query-core/src/__tests__/queriesObserver.test-d.tsx index 0cb59c59e08..e34cfa144ff 100644 --- a/packages/query-core/src/__tests__/queriesObserver.test-d.tsx +++ b/packages/query-core/src/__tests__/queriesObserver.test-d.tsx @@ -1,7 +1,8 @@ import { createKey } from '@tanstack/query-test-utils' +import { selectOption } from '@tanstack/query-test-utils/projection' import { afterEach, beforeEach, describe, expectTypeOf, it } from 'vitest' import { QueriesObserver, QueryClient, defaultQueryFn } from '..' -import type { Query, QueryObserver, QueryObserverResult } from '..' +import type { QueryObserver, QueryObserverResult } from '..' import type { QueriesObserverOptions } from '../queriesObserver' import type { ObserverOptionsInput } from '../queryObserver' @@ -18,14 +19,15 @@ describe('queriesObserver', () => { }) describe('QueriesObserver', () => { - it('should only expose its documented members', () => { - expectTypeOf().toEqualTypeOf< + it('should expose the common observer methods', () => { + expectTypeOf< + Exclude + >().toEqualTypeOf< | 'subscribe' | 'hasListeners' | 'destroy' | 'setQueries' | 'getCurrentResult' - | 'getQueries' | 'getObservers' | 'createResultReader' >() @@ -95,7 +97,7 @@ describe('queriesObserver', () => { it('should reject an option it does not declare', () => { new QueriesObserver(queryClient, [], { // @ts-expect-error combine is the only option - select: (results: Array) => results, + [selectOption]: (results: Array) => results, }) expectTypeOf< @@ -185,14 +187,6 @@ describe('queriesObserver', () => { }) }) - describe('getQueries', () => { - it('should return the observed queries', () => { - const observer = new QueriesObserver(queryClient, []) - - expectTypeOf(observer.getQueries()).toEqualTypeOf>() - }) - }) - describe('getObservers', () => { it('should return the underlying observers', () => { const observer = new QueriesObserver(queryClient, []) diff --git a/packages/query-core/src/__tests__/queriesObserver.test.tsx b/packages/query-core/src/__tests__/queriesObserver.test.tsx index db926c7e274..93f047aaa55 100644 --- a/packages/query-core/src/__tests__/queriesObserver.test.tsx +++ b/packages/query-core/src/__tests__/queriesObserver.test.tsx @@ -1,6 +1,10 @@ import { setFlagsFromString } from 'node:v8' import { runInNewContext } from 'node:vm' import { createKey, sleep } from '@tanstack/query-test-utils' +import { + placeholderOption, + selectOption, +} from '@tanstack/query-test-utils/projection' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { QueriesObserver, QueryClient, QueryObserver, defaultQueryFn } from '..' import type { QueryObserverResult } from '..' @@ -84,7 +88,9 @@ describe('queriesObserver', () => { listener.mockClear() readerB.commit() expect(listener).toHaveBeenCalledTimes(1) - expect(observer.getQueries()[0]!.queryKey).toStrictEqual(keyB) + expect( + observer.getObservers()[0]!.getCurrentQuery().queryKey, + ).toStrictEqual(keyB) listener.mockClear() queryClient.setQueryData(keyA, 3) expect(listener).not.toHaveBeenCalled() @@ -133,7 +139,7 @@ describe('queriesObserver', () => { queryKey: keyB, queryFn: defaultQueryFn, staleTime: Infinity, - select, + [selectOption]: select, structuralSharing: false, } as const const observer = new QueriesObserver(queryClient, [optionsA]) @@ -144,7 +150,9 @@ describe('queriesObserver', () => { expect(select).toHaveBeenCalledTimes(1) expect(observer.getCurrentResult()[0]!.data).toBe(snapshot[0]!.data) expect( - observer.getQueries().map((query) => query.queryKey), + observer + .getObservers() + .map((entry) => entry.getCurrentQuery().queryKey), ).toStrictEqual([keyB, keyA]) unsubscribe() }) @@ -158,7 +166,7 @@ describe('queriesObserver', () => { const options = { queryKey: key, queryFn: defaultQueryFn, - select, + [selectOption]: select, structuralSharing: false, } as const const observer = new QueriesObserver(queryClient, []) @@ -196,7 +204,7 @@ describe('queriesObserver', () => { const reader = observer.createResultReader( queries.map((query) => ({ ...query, - select: (data: number) => data * 10, + [selectOption]: (data: number) => data * 10, })), { combine }, ) @@ -230,7 +238,7 @@ describe('queriesObserver', () => { }) first.commit() const second = observer.createResultReader( - [{ ...options, select: (data: number) => data * 3 }], + [{ ...options, [selectOption]: (data: number) => data * 3 }], { combine }, ) expect(second.combineResult(second.getSnapshot())).toStrictEqual({ @@ -239,7 +247,7 @@ describe('queriesObserver', () => { expect(observer.getCurrentResult()[0]!.data).toBe(2) second.commit() const third = observer.createResultReader( - [{ ...options, select: (data: number) => data * 3 }], + [{ ...options, [selectOption]: (data: number) => data * 3 }], { combine }, ) expect(third.combineResult(third.getSnapshot())).toStrictEqual({ @@ -253,26 +261,26 @@ describe('queriesObserver', () => { const first = { queryKey: createKey(), enabled: false, - placeholderData: 1, + [placeholderOption]: 1, queryFn: defaultQueryFn, } as const const second = { queryKey: createKey(), enabled: false, - placeholderData: 2, + [placeholderOption]: 2, queryFn: defaultQueryFn, } as const const third = { queryKey: createKey(), enabled: false, - placeholderData: 3, + [placeholderOption]: 3, queryFn: defaultQueryFn, } as const const observer = new QueriesObserver(queryClient, [first, second]) const current = observer.getCurrentResult() const optimistic = observer - .createResultReader([{ ...first, placeholderData: 4 }, third]) + .createResultReader([{ ...first, [placeholderOption]: 4 }, third]) .getSnapshot() expect(optimistic.map((result) => result.data)).toStrictEqual([4, 3]) @@ -298,27 +306,6 @@ describe('queriesObserver', () => { expect(observerResult).toMatchObject([{ data: 1 }, { data: 2 }]) }) - it('should return current queries via getQueries', async () => { - const key1 = createKey() - const key2 = createKey() - const queryFn1 = vi.fn<() => number>().mockReturnValue(1) - const queryFn2 = vi.fn<() => number>().mockReturnValue(2) - const observer = new QueriesObserver(queryClient, [ - { queryKey: key1, queryFn: queryFn1 }, - { queryKey: key2, queryFn: queryFn2 }, - ]) - const unsubscribe = observer.subscribe(() => undefined) - await vi.advanceTimersByTimeAsync(0) - - const queries = observer.getQueries() - - expect(queries).toHaveLength(2) - expect(queries[0]?.queryKey).toStrictEqual(key1) - expect(queries[1]?.queryKey).toStrictEqual(key2) - - unsubscribe() - }) - it('should update when a query updates', async () => { const key1 = createKey() const key2 = createKey() @@ -673,12 +660,12 @@ describe('queriesObserver', () => { { queryKey: key1, queryFn: queryFn1, - select: (d: any) => d + 100, + [selectOption]: (d: any) => d + 100, }, { queryKey: key2, queryFn: queryFn2, - select: (d: any) => d + 100, + [selectOption]: (d: any) => d + 100, }, ]) diff --git a/packages/query-core/src/__tests__/queryClient.test-d.tsx b/packages/query-core/src/__tests__/queryClient.test-d.tsx index 4a8e15d3db1..3b65b7d9f9c 100644 --- a/packages/query-core/src/__tests__/queryClient.test-d.tsx +++ b/packages/query-core/src/__tests__/queryClient.test-d.tsx @@ -1,12 +1,13 @@ +import { selectOption } from '@tanstack/query-test-utils/projection' import { assertType, describe, expectTypeOf, it } from 'vitest' import { QueryClient } from '../queryClient' import { skipToken } from '../utils' +import type { DataTag, UnsetMarker } from '..' import type { Mutation } from '../mutation' import type { MutationCache } from '../mutationCache' import type { Query, QueryState } from '../query' import type { QueryCache } from '../queryCache' import type { - DataTag, DefaultError, DefaultOptions, DefaultedQueryObserverOptions, @@ -23,7 +24,6 @@ import type { QueryKey, QueryObserverOptionsBase, SetDataOptions, - UnsetMarker, } from '../types' import type { MutationFilters, QueryFilters, Updater } from '../utils' @@ -361,7 +361,7 @@ describe('queryClient', () => { const result = new QueryClient().query({ queryKey: ['key'], queryFn: () => Promise.resolve('string'), - select: (data) => data.length, + [selectOption]: (data) => data.length, }) expectTypeOf(result).toEqualTypeOf>() @@ -371,7 +371,7 @@ describe('queryClient', () => { const result = new QueryClient().query({ queryKey: ['key'], queryFn: skipToken, - select: (data: string) => data.length, + [selectOption]: (data: string) => data.length, }) expectTypeOf(result).toEqualTypeOf>() @@ -410,7 +410,7 @@ describe('queryClient', () => { queryFn: () => Promise.resolve({ count: 1 }), initialPageParam: 1, getNextPageParam: () => 2, - select: (data) => ({ + [selectOption]: (data) => ({ pages: data.pages.map((x) => `count: ${x.count}`), }), }) @@ -810,7 +810,9 @@ describe('queryClient', () => { it('should infer the passed generic as the tuple data', () => { const queryClient = new QueryClient() - const data = queryClient.getQueriesData({ queryKey: ['key'] }) + const data = queryClient.getQueriesData({ + queryKey: ['key'], + }) expectTypeOf(data).toEqualTypeOf>() }) diff --git a/packages/query-core/src/__tests__/queryClient.test.tsx b/packages/query-core/src/__tests__/queryClient.test.tsx index 08f56f1eb9c..540813a81c7 100644 --- a/packages/query-core/src/__tests__/queryClient.test.tsx +++ b/packages/query-core/src/__tests__/queryClient.test.tsx @@ -1,4 +1,6 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { selectOption } from '@tanstack/query-test-utils/projection' +import { serialScope } from '@tanstack/query-test-utils/scope' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { CancelledError, @@ -797,7 +799,7 @@ describe('queryClient', () => { // @ts-expect-error enabled is not supported for imperative queries enabled: false, staleTime: 0, - select: (data) => `${data}-selected`, + [selectOption]: (data) => `${data}-selected`, }) expect(result).toBe('fetched-data-selected') expect(queryFn).toHaveBeenCalledTimes(1) @@ -832,7 +834,7 @@ describe('queryClient', () => { queryClient.query({ queryKey: key, queryFn: skipToken, - select, + [selectOption]: select, initialData, }), ).resolves.toBeUndefined() @@ -850,7 +852,7 @@ describe('queryClient', () => { const result = await queryClient.query({ queryKey: key, queryFn: skipToken, - select: (data: unknown) => (data as string).length, + [selectOption]: (data: unknown) => (data as string).length, }) expect(result).toBe('cached-data'.length) }) @@ -1101,7 +1103,7 @@ describe('queryClient', () => { queryKey: key, queryFn, staleTime: Infinity, - select: (data) => `${data}-selected`, + [selectOption]: (data) => `${data}-selected`, }) expect(result).toBe('cached-data-selected') expect(queryFn).not.toHaveBeenCalled() @@ -1116,7 +1118,7 @@ describe('queryClient', () => { const result = await queryClient.query({ queryKey: key, queryFn, - select: (data) => data.value.toUpperCase(), + [selectOption]: (data) => data.value.toUpperCase(), }) expect(result).toBe('FETCHED-DATA') expect(queryFn).toHaveBeenCalledTimes(1) @@ -1212,7 +1214,7 @@ describe('queryClient', () => { initialPageParam: 0, // @ts-expect-error enabled is not supported for imperative queries enabled: false, - select: (data) => data.pages.map((page) => `${page}-selected`), + [selectOption]: (data) => data.pages.map((page) => `${page}-selected`), }) expect(result).toStrictEqual(["'fetched-0-selected"]) expect(queryFn).toHaveBeenCalledTimes(1) @@ -1250,7 +1252,7 @@ describe('queryClient', () => { queryFn: skipToken, getNextPageParam: () => undefined, initialPageParam: 0, - select, + [selectOption]: select, }), ).resolves.toBeUndefined() @@ -1349,7 +1351,7 @@ describe('queryClient', () => { getNextPageParam: () => undefined, initialPageParam: 10, queryFn: ({ pageParam }) => Number(pageParam), - select: (data) => data.pages.map((page) => page * 2), + [selectOption]: (data) => data.pages.map((page) => page * 2), }) expect(result).toStrictEqual([20]) }) @@ -1516,7 +1518,10 @@ describe('queryClient', () => { // check the error doesn't occur expect(() => - queryClient.removeQueries({ queryKey: key, exact: true }), + queryClient.removeQueries({ + queryKey: key, + exact: true, + }), ).not.toThrow() // check query was successful removed @@ -1683,7 +1688,10 @@ describe('queryClient', () => { staleTime: Infinity, }) const unsubscribe = observer.subscribe(() => undefined) - await queryClient.refetchQueries({ type: 'active', stale: false }) + await queryClient.refetchQueries({ + type: 'active', + stale: false, + }) unsubscribe() expect(queryFn1).toHaveBeenCalledTimes(2) expect(queryFn2).toHaveBeenCalledTimes(1) @@ -2131,7 +2139,9 @@ describe('queryClient', () => { }) observer.subscribe(() => undefined) - queryClient.refetchQueries(undefined, { cancelRefetch: false }) + queryClient.refetchQueries(undefined, { + cancelRefetch: false, + }) await vi.advanceTimersByTimeAsync(10) observer.destroy() expect(abortFn).toHaveBeenCalledTimes(0) @@ -2487,9 +2497,7 @@ describe('queryClient', () => { const orders: Array = [] const observer1 = new MutationObserver(queryClient, { - scope: { - id: 'scope', - }, + scope: serialScope('scope'), mutationFn: async () => { orders.push('1start') await sleep(50) @@ -2499,9 +2507,7 @@ describe('queryClient', () => { }) const observer2 = new MutationObserver(queryClient, { - scope: { - id: 'scope', - }, + scope: serialScope('scope'), mutationFn: async () => { orders.push('2start') await sleep(20) @@ -2621,9 +2627,7 @@ describe('queryClient', () => { void observer.mutate() const observer2 = new MutationObserver(queryClient, { - scope: { - id: 'scope', - }, + scope: serialScope('scope'), mutationFn: async () => { results.push('mutation2-start') await sleep(50) @@ -2635,9 +2639,7 @@ describe('queryClient', () => { void observer2.mutate() const observer3 = new MutationObserver(queryClient, { - scope: { - id: 'scope', - }, + scope: serialScope('scope'), mutationFn: async () => { results.push('mutation3-start') await sleep(50) diff --git a/packages/query-core/src/__tests__/queryObserver.test-d.tsx b/packages/query-core/src/__tests__/queryObserver.test-d.tsx index 8049ce4ce16..4ac993c7f0a 100644 --- a/packages/query-core/src/__tests__/queryObserver.test-d.tsx +++ b/packages/query-core/src/__tests__/queryObserver.test-d.tsx @@ -1,4 +1,10 @@ import { createKey } from '@tanstack/query-test-utils' +import { refetchInterval } from '@tanstack/query-test-utils/polling' +import { + placeholderOption, + projectionInput, + selectOption, +} from '@tanstack/query-test-utils/projection' import { afterEach, assertType, @@ -8,6 +14,8 @@ import { it, } from 'vitest' import { QueryClient, QueryObserver, defaultQueryFn } from '..' +import type { IntervalInput } from '@tanstack/query-test-utils/polling' +import type { ProjectionInput } from '@tanstack/query-test-utils/projection' import type { DefaultError, DefinedQueryObserverResult, @@ -69,7 +77,7 @@ describe('queryObserver', () => { it('should derive its remaining type parameters from the data type', () => { expectTypeOf< - QueryObserverOptions<{ value: string }>['select'] + ProjectionInput['select']> >().toEqualTypeOf< ((data: { value: string }) => { value: string }) | undefined >() @@ -191,7 +199,7 @@ describe('queryObserver', () => { expectTypeOf(query.state.data).toEqualTypeOf< { value: string } | undefined >() - return false + return refetchInterval(false) }, }) }) @@ -201,18 +209,18 @@ describe('queryObserver', () => { queryKey: createKey(), queryFn: () => Promise.resolve('data'), // @ts-expect-error a refetchInterval callback must return a number, false or undefined - refetchInterval: () => 'often', + refetchInterval: refetchInterval(() => 'often'), }) expectTypeOf< Extract< - QueryObserverOptions['refetchInterval'], + IntervalInput, (...args: Array) => any > >().returns.toEqualTypeOf() expectTypeOf< Exclude< - QueryObserverOptions['refetchInterval'], + IntervalInput, (...args: Array) => any > >().toEqualTypeOf() @@ -474,7 +482,7 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: createKey(), queryFn: () => Promise.resolve({ count: 1 }), - select: (data) => data.count, + [selectOption]: (data) => data.count, }) expectTypeOf(observer.getCurrentResult().data).toEqualTypeOf< @@ -486,7 +494,7 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: createKey(), queryFn: () => ({ count: 1 }), - select: (data) => ({ myCount: data.count }), + [selectOption]: (data) => ({ myCount: data.count }), }) observer.subscribe((result) => { @@ -500,7 +508,7 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: createKey(), queryFn: () => ({ count: 1 }), - select: (data) => ({ myCount: data.count }), + [selectOption]: (data) => ({ myCount: data.count }), }) const observerResult = await observer.refetch() @@ -514,8 +522,8 @@ describe('queryObserver', () => { new QueryObserver(queryClient, { queryKey: createKey(), queryFn: () => Promise.resolve({ count: 1 }), - select: (data) => data.count, - placeholderData: (previousData) => { + [selectOption]: (data) => data.count, + [placeholderOption]: (previousData) => { expectTypeOf(previousData).toEqualTypeOf< { count: number } | undefined >() @@ -530,12 +538,14 @@ describe('queryObserver', () => { }) expectTypeOf< - QueryObserverOptions< - { count: number }, - DefaultError, - number, - { count: number } - >['placeholderData'] + ProjectionInput< + QueryObserverOptions< + { count: number }, + DefaultError, + number, + { count: number } + >['placeholderData'] + > >() .extract<(...args: Array) => any>() .parameter(0) @@ -580,12 +590,14 @@ describe('queryObserver', () => { new QueryObserver(queryClient, { queryKey: createKey(), queryFn: () => Promise.resolve({ value: 'data' }), - placeholderData: { value: 'placeholder' }, + [placeholderOption]: { value: 'placeholder' }, }) expectTypeOf< Exclude< - QueryObserverOptions<{ value: string }>['placeholderData'], + ProjectionInput< + QueryObserverOptions<{ value: string }>['placeholderData'] + >, (...args: Array) => any > >().toEqualTypeOf<{ value: string } | undefined>() @@ -597,7 +609,7 @@ describe('queryObserver', () => { new QueryObserver(queryClient, { queryKey: testQueryKey, queryFn: defaultQueryFn, - placeholderData: (_, previousQuery) => { + [placeholderOption]: (_, previousQuery) => { if (previousQuery) { expectTypeOf(previousQuery.queryKey).toEqualTypeOf< typeof testQueryKey @@ -611,7 +623,7 @@ describe('queryObserver', () => { new QueryObserver(queryClient, { queryKey: createKey(), queryFn: defaultQueryFn, - placeholderData: (_, previousQuery) => { + [placeholderOption]: (_, previousQuery) => { if (previousQuery) { expectTypeOf( previousQuery.state.error, @@ -628,8 +640,8 @@ describe('queryObserver', () => { new QueryObserver(queryClient, { queryKey: createKey(), queryFn: () => queryData, - select: (data) => data.foo, - placeholderData: (previousData) => { + [selectOption]: (data) => data.foo, + [placeholderOption]: (previousData) => { expectTypeOf(previousData).toEqualTypeOf< typeof queryData | undefined >() @@ -1441,7 +1453,7 @@ describe('queryObserver', () => { observer.setOptions({ queryKey: createKey(), queryFn: () => Promise.resolve({ value: 'data' }), - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toEqualTypeOf<{ value: string }>() return data }, @@ -1473,7 +1485,7 @@ describe('queryObserver', () => { >() .parameter(0) .toEqualTypeOf() - expectTypeOf(observer.options.select).toEqualTypeOf< + expectTypeOf(projectionInput(observer.options.select)).toEqualTypeOf< ((data: { value: string }) => { value: string }) | undefined >() }) @@ -1595,7 +1607,7 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: createKey(), queryFn: () => Promise.resolve({ count: 1 }), - select: (data) => data.count, + [selectOption]: (data) => data.count, }) expectTypeOf(observer.getCurrentQuery().state.data).toEqualTypeOf< @@ -1766,12 +1778,13 @@ describe('queryObserver', () => { Promise> >() - expectTypeOf(observer.fetchOptimistic) - .parameter(0) - .toHaveProperty('select') - .toEqualTypeOf< - ((data: { value: string }) => { value: string }) | undefined - >() + expectTypeOf< + ProjectionInput< + Parameters[0]['select'] + > + >().toEqualTypeOf< + ((data: { value: string }) => { value: string }) | undefined + >() }) }) diff --git a/packages/query-core/src/__tests__/queryObserver.test.tsx b/packages/query-core/src/__tests__/queryObserver.test.tsx index 9ce8de6ce59..bb31cf5ab02 100644 --- a/packages/query-core/src/__tests__/queryObserver.test.tsx +++ b/packages/query-core/src/__tests__/queryObserver.test.tsx @@ -1,4 +1,9 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { refetchInterval } from '@tanstack/query-test-utils/polling' +import { + placeholderOption, + selectOption, +} from '@tanstack/query-test-utils/projection' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { QueryClient, @@ -37,7 +42,7 @@ describe('queryObserver', () => { queryKey, queryFn: defaultQueryFn, enabled: false, - select: () => { + [selectOption]: () => { throw new Error('selection failed') }, } as const @@ -152,7 +157,10 @@ describe('queryObserver', () => { it('should not be re-fetched when invalidated with refetchType: all', async () => { const unsubscribe = observer.subscribe(vi.fn()) - queryClient.invalidateQueries({ queryKey: key, refetchType: 'all' }) + queryClient.invalidateQueries({ + queryKey: key, + refetchType: 'all', + }) // So we still expect it to not have fetched and not be fetching expect(count).toBe(0) @@ -222,7 +230,10 @@ describe('queryObserver', () => { unsubscribe() - queryClient.invalidateQueries({ queryKey: key, refetchType: 'active' }) + queryClient.invalidateQueries({ + queryKey: key, + refetchType: 'active', + }) expect(observer.getCurrentResult()).toMatchObject({ status: 'pending', fetchStatus: 'idle', @@ -237,7 +248,10 @@ describe('queryObserver', () => { // Toggle enabled enabled = true - queryClient.invalidateQueries({ queryKey: key, refetchType: 'active' }) + queryClient.invalidateQueries({ + queryKey: key, + refetchType: 'active', + }) expect(observer.getCurrentResult()).toMatchObject({ status: 'pending', fetchStatus: 'fetching', @@ -255,13 +269,19 @@ describe('queryObserver', () => { // Toggle enabled enabled = true - queryClient.invalidateQueries({ queryKey: key, refetchType: 'inactive' }) + queryClient.invalidateQueries({ + queryKey: key, + refetchType: 'inactive', + }) // should not refetch since it was active and we only refetch inactive await vi.advanceTimersByTimeAsync(10) expect(count).toBe(0) - queryClient.invalidateQueries({ queryKey: key, refetchType: 'active' }) + queryClient.invalidateQueries({ + queryKey: key, + refetchType: 'active', + }) // should refetch since it was active and we refetch active await vi.advanceTimersByTimeAsync(10) @@ -271,7 +291,10 @@ describe('queryObserver', () => { enabled = false // should not refetch since it is not active and we only refetch active - queryClient.invalidateQueries({ queryKey: key, refetchType: 'active' }) + queryClient.invalidateQueries({ + queryKey: key, + refetchType: 'active', + }) await vi.advanceTimersByTimeAsync(10) expect(count).toBe(1) @@ -343,7 +366,7 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: () => ({ count: 1 }), - select: (data) => ({ myCount: data.count }), + [selectOption]: (data) => ({ myCount: data.count }), }) let observerResult const unsubscribe = observer.subscribe((result) => { @@ -359,7 +382,7 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: () => ({ count: 1 }), - select: (data) => ({ myCount: data.count }), + [selectOption]: (data) => ({ myCount: data.count }), }) const observerResult = await observer.refetch() expect(observerResult.data).toMatchObject({ myCount: 1 }) @@ -370,7 +393,7 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: () => ({ count: 1 }), - select: (data) => ({ myCount: data.count }), + [selectOption]: (data) => ({ myCount: data.count }), }) let observerResult const unsubscribe = observer.subscribe((result) => { @@ -387,7 +410,7 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: () => ({ count }), - select: (data) => { + [selectOption]: (data) => { count++ return { myCount: data.count } }, @@ -415,7 +438,7 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: key, queryFn, - select: select1, + [selectOption]: select1, }) const unsubscribe = observer.subscribe((result) => { results.push(result) @@ -424,7 +447,7 @@ describe('queryObserver', () => { observer.setOptions({ queryKey: key, queryFn, - select: select2, + [selectOption]: select2, }) await observer.refetch() unsubscribe() @@ -469,7 +492,7 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: key, queryFn, - select, + [selectOption]: select, }) const unsubscribe = observer.subscribe((result) => { results.push(result) @@ -478,7 +501,7 @@ describe('queryObserver', () => { observer.setOptions({ queryKey: key, queryFn, - select, + [selectOption]: select, }) await observer.refetch() unsubscribe() @@ -512,7 +535,7 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: () => ({ count: 1 }), - select: (data) => { + [selectOption]: (data) => { count++ return { myCount: data.count } }, @@ -531,7 +554,7 @@ describe('queryObserver', () => { queryFn: defaultQueryFn, initialData: 'data', enabled: false, - select: () => { + [selectOption]: () => { throw error }, }) @@ -552,7 +575,7 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: key, queryFn, - select: () => { + [selectOption]: () => { throw new Error('selector error') }, }) @@ -591,8 +614,8 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: key, queryFn, - placeholderData: { count: 0 }, - select: () => { + [placeholderOption]: { count: 0 }, + [selectOption]: () => { throw new Error('selector error') }, }) @@ -613,7 +636,7 @@ describe('queryObserver', () => { queryKey: key, retry: 0, queryFn: () => sleep(10).then(() => (shouldError ? 2 : 1)), - select: (num) => { + [selectOption]: (num) => { if (shouldError) { throw error } @@ -662,7 +685,7 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: key1, queryFn: () => sleep(10).then(() => ({ count: 1 })), - select: (): { count: number } => { + [selectOption]: (): { count: number } => { throw new Error('selector error') }, }) @@ -675,7 +698,7 @@ describe('queryObserver', () => { observer.setOptions({ queryKey: key2, queryFn: () => sleep(10).then(() => ({ count: 2 })), - select: (data) => data, + [selectOption]: (data) => data, }) expect(observer.getCurrentResult()).toMatchObject({ status: 'pending', @@ -699,8 +722,8 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: keyA, queryFn: () => sleep(10).then(() => ({ count: 1 })), - placeholderData: placeholder, - select: (data) => ({ selected: data.count }), + [placeholderOption]: placeholder, + [selectOption]: (data) => ({ selected: data.count }), }) const unsubscribe = observer.subscribe(() => {}) await vi.advanceTimersByTimeAsync(10) @@ -712,8 +735,8 @@ describe('queryObserver', () => { observer.setOptions({ queryKey: keyB, queryFn: () => sleep(10).then(() => ({ count: 2 })), - placeholderData: placeholder, - select: (): { selected: number } => { + [placeholderOption]: placeholder, + [selectOption]: (): { selected: number } => { throw new Error('selector error') }, }) @@ -724,8 +747,8 @@ describe('queryObserver', () => { observer.setOptions({ queryKey: keyC, queryFn: () => sleep(10).then(() => ({ count: 3 })), - placeholderData: placeholder, - select: (data) => ({ selected: data.count }), + [placeholderOption]: placeholder, + [selectOption]: (data) => ({ selected: data.count }), }) expect(observer.getCurrentResult()).toMatchObject({ status: 'success', @@ -748,7 +771,7 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: () => sleep(10).then(() => ({ count: 1 })), - select: (data): { count: number } => { + [selectOption]: (data): { count: number } => { if (shouldThrow) { throw new Error('selector error') } @@ -783,7 +806,7 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: () => ({ count: ++count }), - select: () => ({ myCount: 1 }), + [selectOption]: () => ({ myCount: 1 }), }) const observerResult1 = await observer.refetch() const observerResult2 = await observer.refetch() @@ -945,7 +968,7 @@ describe('queryObserver', () => { queryKey: key, queryFn: fetchData, gcTime: 0, - refetchInterval: 10, + refetchInterval: refetchInterval(10), }) const unsubscribe = observer.subscribe(() => undefined) expect(count).toBe(1) @@ -967,7 +990,7 @@ describe('queryObserver', () => { count++ return Promise.resolve('data') }, - refetchInterval: () => 10, + refetchInterval: refetchInterval(() => 10), }) const unsubscribe = observer.subscribe(() => undefined) expect(count).toBe(1) @@ -979,15 +1002,15 @@ describe('queryObserver', () => { it('should call refetchInterval with the query when it is a function', async () => { const key = createKey() - const refetchInterval = vi.fn<() => number>(() => 10) + const getInterval = vi.fn<() => number>(() => 10) const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: () => sleep(10).then(() => 'data'), - refetchInterval, + refetchInterval: refetchInterval(getInterval), }) const unsubscribe = observer.subscribe(() => undefined) await vi.advanceTimersByTimeAsync(10) - expect(refetchInterval).toHaveBeenCalledWith( + expect(getInterval).toHaveBeenCalledWith( queryClient.getQueryCache().find({ queryKey: key }), ) @@ -1039,7 +1062,7 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: () => 'data', - placeholderData: 'placeholder', + [placeholderOption]: 'placeholder', }) expect(observer.getCurrentResult()).toMatchObject({ @@ -1066,7 +1089,7 @@ describe('queryObserver', () => { queryKey: key, enabled: false, queryFn: () => 'data', - placeholderData: {}, + [placeholderOption]: {}, }) const firstData = observer.getCurrentResult().data @@ -1074,7 +1097,7 @@ describe('queryObserver', () => { observer.setOptions({ queryKey: key, queryFn: defaultQueryFn, - placeholderData: {}, + [placeholderOption]: {}, }) const secondData = observer.getCurrentResult().data @@ -1137,7 +1160,7 @@ describe('queryObserver', () => { queryKey: key, queryFn, refetchIntervalInBackground: false, - refetchInterval: 10, + refetchInterval: refetchInterval(10), }) const unsubscribe = observer.subscribe(() => undefined) @@ -1158,7 +1181,7 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: () => data, - select: () => data, + [selectOption]: () => data, }) const unsubscribe = observer.subscribe(() => undefined) @@ -1169,7 +1192,7 @@ describe('queryObserver', () => { queryKey: key, queryFn: () => data, structuralSharing: false, - select: () => selectedData, + [selectOption]: () => selectedData, }) await observer.refetch() @@ -1190,25 +1213,25 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: () => data, - select: () => data, + [selectOption]: () => data, }) observer.setOptions({ queryKey: key, queryFn: () => data, - select: () => { + [selectOption]: () => { return selectedData1 }, - placeholderData: placeholderData1, + [placeholderOption]: placeholderData1, }) observer.setOptions({ queryKey: key, queryFn: () => data, - select: () => { + [selectOption]: () => { return selectedData2 }, - placeholderData: placeholderData2, + [placeholderOption]: placeholderData2, structuralSharing: false, }) expect(observer.getCurrentResult().data).toBe(selectedData2) @@ -1227,11 +1250,11 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: key1, queryFn: () => data1, - placeholderData: (prev, prevQuery) => { + [placeholderOption]: (prev, prevQuery) => { keys.push(prevQuery?.queryKey || null) return prev }, - select: (data) => data.value, + [selectOption]: (data) => data.value, }) const unsubscribe = observer.subscribe((result) => { @@ -1242,11 +1265,11 @@ describe('queryObserver', () => { observer.setOptions({ queryKey: key2, queryFn: () => data2, - placeholderData: (prev, prevQuery) => { + [placeholderOption]: (prev, prevQuery) => { keys.push(prevQuery?.queryKey || null) return prev }, - select: (data) => data.value, + [selectOption]: (data) => data.value, }) await vi.advanceTimersByTimeAsync(0) unsubscribe() @@ -1292,8 +1315,8 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: key1, queryFn: () => data1, - placeholderData: (prev) => prev, - select: (data) => { + [placeholderOption]: (prev) => prev, + [selectOption]: (data) => { selectCount++ return data.value }, @@ -1307,8 +1330,8 @@ describe('queryObserver', () => { observer.setOptions({ queryKey: key2, queryFn: () => data2, - placeholderData: (prev) => prev, - select: (data) => { + [placeholderOption]: (prev) => prev, + [selectOption]: (data) => { selectCount++ return data.value }, @@ -1358,8 +1381,8 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: key1, queryFn: () => data1, - placeholderData: (prev) => prev, - select: stableSelect, + [placeholderOption]: (prev) => prev, + [selectOption]: stableSelect, }) const unsubscribe = observer.subscribe((result) => { @@ -1370,8 +1393,8 @@ describe('queryObserver', () => { observer.setOptions({ queryKey: key2, queryFn: () => data2, - placeholderData: (prev) => prev, - select: stableSelect, + [placeholderOption]: (prev) => prev, + [selectOption]: stableSelect, }) await vi.advanceTimersByTimeAsync(0) unsubscribe() @@ -1418,7 +1441,7 @@ describe('queryObserver', () => { queryKey: key, queryFn: defaultQueryFn, enabled: false, - refetchInterval: 10, + refetchInterval: refetchInterval(10), }) const query = queryClient.getQueryCache().find({ queryKey: key }) @@ -1456,7 +1479,7 @@ describe('queryObserver', () => { queryFn: defaultQueryFn, enabled: false, staleTime: 10, - refetchInterval: 10, + refetchInterval: refetchInterval(10), }) const setTimeoutSpy = vi.spyOn(timeoutManager, 'setTimeout') const setIntervalSpy = vi.spyOn(timeoutManager, 'setInterval') @@ -1479,7 +1502,7 @@ describe('queryObserver', () => { queryKey: key, queryFn: defaultQueryFn, staleTime: 10, - refetchInterval: 10, + refetchInterval: refetchInterval(10), }) const setTimeoutSpy = vi.spyOn(timeoutManager, 'setTimeout') const setIntervalSpy = vi.spyOn(timeoutManager, 'setInterval') @@ -2061,8 +2084,9 @@ describe('queryObserver', () => { queryKey: [...key, id], queryFn: () => [id], enabled: id !== '', - placeholderData: keepPreviousData, - select: (items: Array) => items.find((item) => item === id), + [placeholderOption]: keepPreviousData, + [selectOption]: (items: Array) => + items.find((item) => item === id), }) const observer = new QueryObserver(queryClient, options('a')) const unsubscribe = observer.subscribe(() => undefined) @@ -2086,7 +2110,10 @@ describe('queryObserver', () => { } // A new placeholderData is not memoized, so its undefined means pending - observer.setOptions({ ...options(''), placeholderData: () => undefined }) + observer.setOptions({ + ...options(''), + [placeholderOption]: () => undefined, + }) expect(observer.getCurrentResult()).toMatchObject({ status: 'pending', isPlaceholderData: false, diff --git a/packages/query-core/src/__tests__/queryObserverProjection.test.ts b/packages/query-core/src/__tests__/queryObserverProjection.test.ts index 558c04f0e2b..ee94a4fd1d1 100644 --- a/packages/query-core/src/__tests__/queryObserverProjection.test.ts +++ b/packages/query-core/src/__tests__/queryObserverProjection.test.ts @@ -1,4 +1,8 @@ import { createKey } from '@tanstack/query-test-utils' +import { + placeholderOption, + selectOption, +} from '@tanstack/query-test-utils/projection' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { QueryClient, QueryObserver, defaultQueryFn, noop } from '..' @@ -21,8 +25,8 @@ describe('observer data outcome after reset', () => { queryKey: key, queryFn: () => new Promise<{ label: string | null }>(() => {}), enabled: false, - placeholderData: placeholder, - select: (row) => { + [placeholderOption]: placeholder, + [selectOption]: (row) => { if (row.label === null) throw new Error('label not ready') return row.label }, @@ -57,8 +61,8 @@ describe('observer data outcome after reset', () => { queryKey: key, queryFn: defaultQueryFn, enabled: false, - placeholderData: { label: null }, - select, + [placeholderOption]: { label: null }, + [selectOption]: select, } as const queryClient.setQueryData(key, { label: 'first' }) const observer = new QueryObserver(queryClient, options) @@ -104,7 +108,10 @@ describe('observer callback errors', () => { const placeholderData = vi.fn<() => never>(() => { throw new Error('placeholder failed') }) - const reader = observer.createResultReader({ ...options, placeholderData }) + const reader = observer.createResultReader({ + ...options, + [placeholderOption]: placeholderData, + }) try { const result = reader.getSnapshot() @@ -143,7 +150,7 @@ describe('observer callback errors', () => { } as const const observer = new QueryObserver(client, { ...options, - select: () => { + [selectOption]: () => { throw undefined }, }) @@ -170,7 +177,7 @@ describe('observer callback errors', () => { queryKey: createKey(), initialData: 1, enabled: false, - select: (value: number) => value * 2, + [selectOption]: (value: number) => value * 2, }) const observer = new QueryObserver(client, options) const reader = observer.createResultReader({ @@ -196,7 +203,7 @@ describe('observer callback errors', () => { const options = client.defaultQueryOptions<{ value: number }>({ queryKey: createKey(), enabled: false, - placeholderData, + [placeholderOption]: placeholderData, structuralSharing: false, }) const observer = new QueryObserver(client, options) @@ -213,7 +220,7 @@ describe('observer callback errors', () => { const secondReader = observer.createResultReader({ ...options, - placeholderData: () => placeholderData(), + [placeholderOption]: () => placeholderData(), }) const second = secondReader.getSnapshot() expect(secondReader.getSnapshot()).toBe(second) diff --git a/packages/query-core/src/__tests__/queryObserverResultReader.test-d.tsx b/packages/query-core/src/__tests__/queryObserverResultReader.test-d.tsx index 03a5a85fe1e..ce0a3bfca2f 100644 --- a/packages/query-core/src/__tests__/queryObserverResultReader.test-d.tsx +++ b/packages/query-core/src/__tests__/queryObserverResultReader.test-d.tsx @@ -1,3 +1,4 @@ +import { selectOption } from '@tanstack/query-test-utils/projection' import { describe, expectTypeOf, it } from 'vitest' import { InfiniteQueryObserver, QueryClient, QueryObserver } from '..' import type { @@ -23,7 +24,7 @@ describe('result reader types', () => { >({ queryKey: ['value'], queryFn: () => 1, - select: String, + [selectOption]: String, }) const observer = new QueryObserver(client, options) const reader = observer.createResultReader(options) @@ -46,7 +47,7 @@ describe('result reader types', () => { > = { queryKey: ['value'], queryFn: ({ pageParam }) => pageParam, - select: (data) => data.pages.join(','), + [selectOption]: (data) => data.pages.join(','), initialPageParam: 0, getNextPageParam: (last) => last + 1, queryHash: 'value', diff --git a/packages/query-core/src/__tests__/queryObserverResultReader.test.tsx b/packages/query-core/src/__tests__/queryObserverResultReader.test.tsx index b87d8233c2b..d8b7de29a13 100644 --- a/packages/query-core/src/__tests__/queryObserverResultReader.test.tsx +++ b/packages/query-core/src/__tests__/queryObserverResultReader.test.tsx @@ -1,4 +1,8 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { + placeholderOption, + selectOption, +} from '@tanstack/query-test-utils/projection' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { InfiniteQueryObserver, @@ -35,7 +39,7 @@ describe('query observer result readers', () => { const options = client.defaultQueryOptions({ queryKey: keyA, enabled: false, - select, + [selectOption]: select, }) const observer = new QueryObserver(client, options) const listener = vi.fn<() => void>() @@ -51,7 +55,7 @@ describe('query observer result readers', () => { ...options, queryKey: keyB, queryHash: undefined, - select: (data) => ({ selected: data.value * 10 }), + [selectOption]: (data) => ({ selected: data.value * 10 }), }), ) @@ -177,7 +181,7 @@ describe('query observer result readers', () => { queryKey: createKey(), initialData: { value: 1 }, enabled: false, - select: (data: { value: number }) => data.value, + [selectOption]: (data: { value: number }) => data.value, }) const observer = new QueryObserver(client, options) const current = observer.getCurrentResult() @@ -185,7 +189,10 @@ describe('query observer result readers', () => { const select = vi.fn<() => never>(() => { throw error }) - const reader = observer.createResultReader({ ...options, select }) + const reader = observer.createResultReader({ + ...options, + [selectOption]: select, + }) const snapshot = reader.getSnapshot() await vi.advanceTimersByTimeAsync(10) expect(reader.getSnapshot()).toBe(snapshot) @@ -207,7 +214,7 @@ describe('query observer result readers', () => { const options = client.defaultQueryOptions({ queryKey: key, enabled: false, - select, + [selectOption]: select, structuralSharing: false, }) const observer = new QueryObserver(client, options) @@ -243,7 +250,7 @@ describe('query observer result readers', () => { const options = client.defaultQueryOptions({ queryKey: key, enabled: false, - select, + [selectOption]: select, }) const observer = new QueryObserver(client, options) const reader = observer.createResultReader(options) @@ -261,7 +268,7 @@ describe('query observer result readers', () => { queryKey: createKey(), queryFn: () => ({ value: 1 }), enabled: false, - select: (data: { value: number }) => data.value, + [selectOption]: (data: { value: number }) => data.value, }) const observer = new QueryObserver(client, options) const placeholderData = vi.fn<() => { value: number }>(() => ({ value: 2 })) @@ -270,8 +277,8 @@ describe('query observer result readers', () => { }) const reader = observer.createResultReader({ ...options, - placeholderData, - select, + [placeholderOption]: placeholderData, + [selectOption]: select, }) const snapshot = reader.getSnapshot() await vi.advanceTimersByTimeAsync(10) @@ -285,7 +292,7 @@ describe('query observer result readers', () => { queryKey: createKey(), initialData: { value: 1 }, enabled: false, - select: (data: { value: number }) => ({ selected: data.value }), + [selectOption]: (data: { value: number }) => ({ selected: data.value }), }) const observer = new QueryObserver(client, options) const select = vi.fn<(data: { value: number }) => { selected: number }>( @@ -295,7 +302,10 @@ describe('query observer result readers', () => { ) const listener = vi.fn<() => void>() const unsubscribe = observer.subscribe(listener) - const reader = observer.createResultReader({ ...options, select }) + const reader = observer.createResultReader({ + ...options, + [selectOption]: select, + }) const snapshot = reader.getSnapshot() reader.commit() expect(observer.getCurrentResult().data).toBe(snapshot.data) @@ -323,7 +333,7 @@ describe('query observer result readers', () => { initialData: undefined, queryKey: createKey(), enabled: false, - placeholderData, + [placeholderOption]: placeholderData, }), ) const snapshot = reader.getSnapshot() @@ -349,7 +359,7 @@ describe('query observer result readers', () => { queryKey: createKey(), queryFn: () => ({ value: 0 }), enabled: false, - placeholderData, + [placeholderOption]: placeholderData, }) const observer = new QueryObserver(client, options) expect( @@ -359,7 +369,7 @@ describe('query observer result readers', () => { }) const withoutPlaceholder = observer.createResultReader({ ...options, - placeholderData: undefined, + [placeholderOption]: undefined, }) withoutPlaceholder.commit() expect(withoutPlaceholder.getSnapshot().data).toBeUndefined() diff --git a/packages/query-core/src/__tests__/timeoutManager.test.tsx b/packages/query-core/src/__tests__/timeoutManager.test.tsx index 288e67cd9e9..2765f4815e5 100644 --- a/packages/query-core/src/__tests__/timeoutManager.test.tsx +++ b/packages/query-core/src/__tests__/timeoutManager.test.tsx @@ -1,9 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - TimeoutManager, - defaultTimeoutProvider, - timeoutManager, -} from '../timeoutManager' +import { TimeoutManager, timeoutManager } from '../timeoutManager' import type { MockInstance } from 'vitest' import type { TimeoutCallback, TimeoutProvider } from '../timeoutManager' @@ -110,17 +106,4 @@ describe('timeoutManager', () => { expect(timeoutManager).toBeInstanceOf(TimeoutManager) }) }) - - describe('exported functions', () => { - let provider: ReturnType - - beforeEach(() => { - provider = createMockProvider() - timeoutManager.setTimeoutProvider(provider) - }) - - afterEach(() => { - timeoutManager.setTimeoutProvider(defaultTimeoutProvider) - }) - }) }) diff --git a/packages/query-core/src/__tests__/utils.test-d.tsx b/packages/query-core/src/__tests__/utils.test-d.tsx index 1faad148309..7fc9ca752b4 100644 --- a/packages/query-core/src/__tests__/utils.test-d.tsx +++ b/packages/query-core/src/__tests__/utils.test-d.tsx @@ -24,16 +24,10 @@ import { sleep, timeUntilStale, } from '../utils' +import type { DataTag, EqualityFn, MutationStatus } from '..' import type { Mutation } from '../mutation' import type { Query } from '../query' -import type { - DataTag, - EqualityFn, - MutationStatus, - QueryFunction, - QueryKey, - QueryOptions, -} from '../types' +import type { QueryFunction, QueryKey, QueryOptions } from '../types' import type { DefaultQueryFn, MutationFilters, @@ -125,9 +119,10 @@ describe('QueryFilters', () => { const queryKey: Key = ['foo', 'bar'] as any as Key - expectTypeOf(new QueryClient().invalidateQueries).toBeCallableWith({ + const result = new QueryClient().invalidateQueries({ queryKey, }) + expectTypeOf(result).toEqualTypeOf>() }) it('should error on invalid query keys', () => { diff --git a/packages/query-core/src/primitives.ts b/packages/query-core/src/primitives.ts new file mode 100644 index 00000000000..548cdb09166 --- /dev/null +++ b/packages/query-core/src/primitives.ts @@ -0,0 +1,57 @@ +// Shared runtime for adapters with their own query clients and observers. +export { environmentManager, isServer } from './environmentManager' +export type { IsServerValue } from './environmentManager' +export { FocusManager, focusManager } from './focusManager' +export { OnlineManager, onlineManager } from './onlineManager' +export type { Action as MutationAction } from './mutation' +export type { + Action as QueryAction, + FetchDirection, + FetchMeta, + FetchOptions, +} from './query' +export { fetchState, getDefaultQueryState, successState } from './queryState' +export { Removable } from './removable' +export { CancelledError, canFetch, createRetryer } from './retryer' +export type { Retryer, RetryDelayValue, RetryValue } from './retryer' +export { Subscribable } from './subscribable' +export { + TimeoutManager, + defaultTimeoutProvider, + timeoutManager, +} from './timeoutManager' +export type { + ManagedTimerId, + TimeoutCallback, + TimeoutProvider, +} from './timeoutManager' +export { dataTagSymbol, dataTagErrorSymbol, unsetMarker } from './types' +export type { QueryObserverOptionsBase } from './types' +export { + addConsumeAwareSignal, + addToArray, + defaultQueryFn, + fetchSignal, + functionalUpdate, + hashKey, + hashKeyByOptions, + isPlainArray, + isPlainObject, + isValidTimeout, + noop, + partialMatchKey, + replaceData, + replaceEqualDeep, + shallowEqualObjects, + shouldThrowError, + skipToken, + sleep, + timeUntilStale, +} from './utils' +export type { + DefaultQueryFn, + FetchSignalContext, + QueryTypeFilter, + SkipToken, + Updater, +} from './utils' diff --git a/packages/query-core/src/query.ts b/packages/query-core/src/query.ts index 24bff3a6f95..6c9c66950d4 100644 --- a/packages/query-core/src/query.ts +++ b/packages/query-core/src/query.ts @@ -1,7 +1,8 @@ import { infiniteQueryBehavior } from './infiniteQueryBehavior' import { notifyManager } from './notifyManager' +import { fetchState, getDefaultQueryState, successState } from './queryState' import { Removable } from './removable' -import { CancelledError, canFetch, createRetryer } from './retryer' +import { CancelledError, createRetryer } from './retryer' import { ensureQueryFn, fetchSignal, @@ -19,7 +20,6 @@ import type { CancelOptions, DefaultError, FetchStatus, - InitialDataFunction, QueryKey, QueryMeta, QueryOptions, @@ -312,7 +312,7 @@ export class Query< this.#cache = this.#client.getQueryCache() this.queryKey = config.queryKey this.queryHash = config.queryHash - this.#initialState = getDefaultState(this.options) + this.#initialState = getDefaultQueryState(this.options) this.state = config.state ?? this.#initialState this.scheduleGc() } @@ -361,7 +361,7 @@ export class Query< // oxlint-disable-next-line typescript/no-unnecessary-condition -- the constructor calls 'setOptions' before it assigns 'state' if (this.state && this.state.data === undefined) { - const defaultState = getDefaultState(this.options) + const defaultState = getDefaultQueryState(this.options) if (defaultState.data !== undefined) { this.setState( successState(defaultState.data, defaultState.dataUpdatedAt), @@ -1018,90 +1018,4 @@ export class Query< } } -/** - * Returns the state changes applied when a query starts fetching. - * @param data - The query's current data. If it is `undefined`, the query is also reset to - * `'pending'` with no error. - * @param options - The query options, whose `networkMode` decides whether the query is `'fetching'` - * or `'paused'`. - * @returns The partial query state for a starting fetch. - */ -export function fetchState< - TQueryFnData, - TError, - TData, - TQueryKey extends QueryKey, ->( - data: TData | undefined, - options: QueryOptions, -) { - return { - fetchFailureCount: 0, - fetchFailureReason: null, - fetchStatus: canFetch(options.networkMode) ? 'fetching' : 'paused', - ...(data === undefined && - ({ - error: null, - status: 'pending', - } as const)), - } as const -} - -/** - * Returns the state changes applied when a query receives data. - * @param data - The new data. - * @param dataUpdatedAt - The timestamp the data is recorded with. Defaults to the current time. - * @returns The partial query state for a successful update. - */ -function successState(data: TData | undefined, dataUpdatedAt?: number) { - return { - data, - dataUpdatedAt: dataUpdatedAt ?? Date.now(), - error: null, - isInvalidated: false, - status: 'success' as const, - } -} - -/** - * Returns the initial state of a query, based on its `initialData` and `initialDataUpdatedAt` - * options. - * @param options - The query options. - * @returns The initial query state: `'success'` if `initialData` is set, otherwise `'pending'`. - */ -function getDefaultState< - TQueryFnData, - TError, - TData, - TQueryKey extends QueryKey, ->( - options: QueryOptions, -): QueryState { - const data = - typeof options.initialData === 'function' - ? (options.initialData as InitialDataFunction)() - : options.initialData - - const hasData = data !== undefined - - const initialDataUpdatedAt = hasData - ? typeof options.initialDataUpdatedAt === 'function' - ? options.initialDataUpdatedAt() - : options.initialDataUpdatedAt - : 0 - - return { - data, - dataUpdateCount: 0, - dataUpdatedAt: hasData ? (initialDataUpdatedAt ?? Date.now()) : 0, - error: null, - errorUpdateCount: 0, - errorUpdatedAt: 0, - fetchFailureCount: 0, - fetchFailureReason: null, - fetchMeta: null, - isInvalidated: false, - status: hasData ? 'success' : 'pending', - fetchStatus: 'idle', - } -} +export { fetchState } from './queryState' diff --git a/packages/query-core/src/queryObserver.ts b/packages/query-core/src/queryObserver.ts index a76cfc492d8..aecb095aa7f 100644 --- a/packages/query-core/src/queryObserver.ts +++ b/packages/query-core/src/queryObserver.ts @@ -1,7 +1,7 @@ import { isServer as isServerEnvironment } from './environmentManager' import { focusManager } from './focusManager' import { notifyManager } from './notifyManager' -import { fetchState } from './query' +import { fetchState } from './queryState' import { Subscribable } from './subscribable' import { timeoutManager } from './timeoutManager' import { diff --git a/packages/query-core/src/queryState.ts b/packages/query-core/src/queryState.ts new file mode 100644 index 00000000000..cf8b318a0ce --- /dev/null +++ b/packages/query-core/src/queryState.ts @@ -0,0 +1,84 @@ +import { canFetch } from './retryer' +import type { QueryState } from './query' +import type { InitialDataFunction, QueryOptions } from './types' + +/** + * Returns the state changes applied when a query starts fetching. + * @param data - The query's current data. If it is `undefined`, the query is also reset to + * `'pending'` with no error. + * @param options - The query options, whose `networkMode` decides whether the query is `'fetching'` + * or `'paused'`. + * @returns The partial query state for a starting fetch. + */ +export function fetchState( + data: TData | undefined, + options: Pick, +) { + return { + fetchFailureCount: 0, + fetchFailureReason: null, + fetchStatus: canFetch(options.networkMode) ? 'fetching' : 'paused', + ...(data === undefined && + ({ + error: null, + status: 'pending', + } as const)), + } as const +} + +/** + * Returns the state changes applied when a query receives data. + * @param data - The new data. + * @param dataUpdatedAt - The timestamp the data is recorded with. Defaults to the current time. + * @returns The partial query state for a successful update. + */ +export function successState( + data: TData | undefined, + dataUpdatedAt?: number, +) { + return { + data, + dataUpdatedAt: dataUpdatedAt ?? Date.now(), + error: null, + isInvalidated: false, + status: 'success' as const, + } +} + +/** + * Returns the initial state of a query, based on its `initialData` and `initialDataUpdatedAt` + * options. + * @param options - Supplies the initial cache value and its update time. + * @returns The initial query state: `'success'` if `initialData` is set, otherwise `'pending'`. + */ +export function getDefaultQueryState( + options: Pick, 'initialData' | 'initialDataUpdatedAt'>, +): QueryState { + const data = + typeof options.initialData === 'function' + ? (options.initialData as InitialDataFunction)() + : options.initialData + + const hasData = data !== undefined + + const initialDataUpdatedAt = hasData + ? typeof options.initialDataUpdatedAt === 'function' + ? options.initialDataUpdatedAt() + : options.initialDataUpdatedAt + : 0 + + return { + data, + dataUpdateCount: 0, + dataUpdatedAt: hasData ? (initialDataUpdatedAt ?? Date.now()) : 0, + error: null, + errorUpdateCount: 0, + errorUpdatedAt: 0, + fetchFailureCount: 0, + fetchFailureReason: null, + fetchMeta: null, + isInvalidated: false, + status: hasData ? 'success' : 'pending', + fetchStatus: 'idle', + } +} diff --git a/packages/query-core/src/utils.ts b/packages/query-core/src/utils.ts index 7f39a202c20..3181666bdb2 100644 --- a/packages/query-core/src/utils.ts +++ b/packages/query-core/src/utils.ts @@ -595,7 +595,7 @@ export function sleep(timeout: number): Promise { */ export function replaceData< TData, - TOptions extends QueryOptions, + TOptions extends Pick, >(prevData: TData | undefined, data: TData, options: TOptions): TData { if (typeof options.structuralSharing === 'function') { return options.structuralSharing(prevData, data) as TData diff --git a/packages/query-test-utils/package.json b/packages/query-test-utils/package.json index e8fe8451f00..c1e250169a3 100644 --- a/packages/query-test-utils/package.json +++ b/packages/query-test-utils/package.json @@ -23,7 +23,10 @@ "types": "./src/index.ts", "default": "./src/index.ts" }, - "./package.json": "./package.json" + "./package.json": "./package.json", + "./polling": "./src/polling.ts", + "./scope": "./src/scope.ts", + "./projection": "./src/projection.ts" }, "scripts": { "clean": "premove ./build ./coverage ./dist-ts ./.cache/test-types", diff --git a/packages/query-test-utils/src/polling.ts b/packages/query-test-utils/src/polling.ts new file mode 100644 index 00000000000..2ceadbc34ec --- /dev/null +++ b/packages/query-test-utils/src/polling.ts @@ -0,0 +1,12 @@ +/** + * Supplies the interval directly to the v6 query options. + * The pluggable compatibility suite uses its own public factory here. + * @param option - Interval setting from a shared test case. + * @returns The supplied setting with its original type. + */ +export function refetchInterval(option: T): T { + return option +} + +/** Input accepted by the polling option in this implementation. */ +export type IntervalInput = TOption diff --git a/packages/query-test-utils/src/projection.ts b/packages/query-test-utils/src/projection.ts new file mode 100644 index 00000000000..59a47430228 --- /dev/null +++ b/packages/query-test-utils/src/projection.ts @@ -0,0 +1,23 @@ +/** Marks a query selector in suites shared by adapters with different option syntax. */ +export const selectOption = 'select' + +/** Marks a query placeholder in suites shared by adapters with different option syntax. */ +export const placeholderOption = 'placeholderData' + +/** Input of a projection option in the standard observer. */ +export type ProjectionInput = T + +/** + * Reads the selector or placeholder supplied to the standard observer. + * @param option - Value exposed through the observer options. + * @returns The original input for a projection type assertion. + */ +export function projectionInput(option: T): T { + return option +} + +/** A stored selection option for an adapter-agnostic React test. */ +export type SelectSetting = TValue + +/** A stored placeholder option for an adapter-agnostic React test. */ +export type PlaceholderSetting = TValue diff --git a/packages/query-test-utils/src/scope.ts b/packages/query-test-utils/src/scope.ts new file mode 100644 index 00000000000..713b159d246 --- /dev/null +++ b/packages/query-test-utils/src/scope.ts @@ -0,0 +1,8 @@ +/** + * Creates a serial scope for the canonical and integrated v6 runtimes. + * @param id - The shared queue ID. + * @returns The scope option used by the v6 mutation cache. + */ +export function serialScope(id: string): { id: string } { + return { id } +} diff --git a/packages/react-query-pluggable/README.md b/packages/react-query-pluggable/README.md new file mode 100644 index 00000000000..fc3a6113d2d --- /dev/null +++ b/packages/react-query-pluggable/README.md @@ -0,0 +1,168 @@ +# @tanstack/react-query-pluggable + +An experimental ESM React Query adapter for React 19. A `QueryClient` holds cache state and configuration. Import client operations and optional query features where you use them. + +The adapter uses `@tanstack/query-core` for fetching retries, cancellation, garbage collection, key comparison and structural sharing. It also uses the same focus, online, timeout and environment managers as the other adapters. Configuring one of those managers affects every adapter that uses that copy of core. + +```tsx +import { + QueryClient, + QueryClientProvider, + refetchInterval, + useQuery, +} from '@tanstack/react-query-pluggable' + +const client = new QueryClient() + +function Orders() { + const { data } = useQuery({ + queryKey: ['orders'], + queryFn: fetchOrders, + refetchInterval: refetchInterval(3000), + }) + return

    {data?.length} orders

    +} + +export function App() { + return ( + + + + ) +} +``` + +`useQuery`, `useInfiniteQuery`, `useSuspenseQuery` and `useSuspenseInfiniteQuery` accept the same helper, as do query defaults. Pass a callback to compute the next interval from the cached query. Return `false` or `undefined` to stop polling. + +```ts +useQuery({ + queryKey: ['job', jobId], + queryFn: () => fetchJob(jobId), + refetchInterval: (query) => + query.state.data?.status === 'complete' ? false : refetchInterval(3000), +}) +``` + +Polling runs while an enabled observer has subscribers and the window is focused. Set `refetchIntervalInBackground: true` to keep polling in the background. Each observer manages its own timer, including when several observers share a client default. + +## Choosing how a query renders + +`useQuery(query(options))` returns a pending result while an uncached query loads. Pass +`suspenseQuery(options)` to the same hook to show the nearest React `` fallback +until data is available. Both readers use the same client and cache key. The `query` export +is an alias of `queryOptions`. Only `suspenseQuery` imports the single-query Suspense policy. + +```tsx +import { query, suspenseQuery, useQuery } from '@tanstack/react-query-pluggable' + +const postOptions = (id: number) => + query({ queryKey: ['post', id], queryFn: () => fetchPost(id) }) + +function PostPreview({ id }: { id: number }) { + const post = useQuery(postOptions(id)) + return

    {post.isPending ? 'Loading…' : post.data?.title}

    +} + +// Render inside Loading…

    }>. +function PostTitle({ id }: { id: number }) { + const post = useQuery(suspenseQuery(postOptions(id))) + return

    {post.data.title}

    +} +``` + +The Suspense policy sends a failed query without cached data to the nearest error boundary. +Passing `skipToken` skips the fetch and can yield undefined data. `useSuspenseQuery(options)` +is a shorthand for `useQuery(suspenseQuery(options))`. + +### Paginated queries with the same hook + +Build the observer with `infiniteQuery`. Wrap those options in `suspenseQuery` when React +should show a parent fallback while loading the first page. Both forms expose `fetchNextPage`, +`hasNextPage`, and the cached `pages` and `pageParams`. + +```tsx +import { + infiniteQuery, + suspenseQuery, + useQuery, +} from '@tanstack/react-query-pluggable' + +const postPages = infiniteQuery({ + queryKey: ['posts', 'pages'], + initialPageParam: 0, + queryFn: ({ pageParam }) => fetchPostPage(pageParam), + getNextPageParam: (lastPage) => lastPage.nextCursor, +}) + +function Posts() { + const result = useQuery(suspenseQuery(postPages)) + return ( + <> + {result.data.pages.map((page) => ( + + ))} + + + ) +} +``` + +Use `useQuery(postPages)` to handle the pending state inside the component. Outside React, import +`fetchInfiniteQuery` to fetch and cache pages by calling `fetchInfiniteQuery(client, postPages)`. + +## Selecting and keeping data + +`select` maps the cached value for one observer. `placeholderData` supplies a temporary value for a pending query. Wrap a typed selector in `select(getTitle)`, or use the tuple form to infer an inline callback's argument from the query. For example, this hook keeps displaying the previous post title while the next post loads. + +```tsx +import { + keepPreviousData, + placeholderData, + select, + useQuery, +} from '@tanstack/react-query-pluggable' + +function usePostTitle(id: number) { + return useQuery({ + queryKey: ['post', id], + queryFn: () => fetchPost(id), // Promise<{ title: string }> + select: [select, (post) => post.title], + placeholderData: placeholderData(keepPreviousData), + }) +} +``` + +## Client operations + +The `QueryClient` constructor creates the state shared by hooks, providers and imperative callers. All operations on that client are named functions. Pass the client first, followed by the arguments you would pass to the v6 method. + +```ts +import { + fetchQuery, + fetchInfiniteQuery, + getQueryData, + invalidateQueries, + setQueryData, +} from '@tanstack/react-query-pluggable' + +const order = await fetchQuery(client, orderOptions) +const cached = getQueryData(client, orderOptions.queryKey) +setQueryData(client, orderOptions.queryKey, updatedOrder) +await fetchInfiniteQuery(client, orderPageOptions) +await invalidateQueries(client, { queryKey: ['orders'] }) +``` + +For example, `client.query(options)` becomes `fetchQuery(client, options)` and `client.clear()` becomes `clearQueryClient(client)`. The provider manages mounting for React users. Integrations that managed the v6 lifecycle directly can call `mountQueryClient(client)` and `unmountQueryClient(client)`. The same client-first convention applies to defaults, mutation resumption and bulk cache operations. + +Use `getQueryCache(client)` and `getMutationCache(client)` for direct cache access. Cache objects keep methods such as `.subscribe(listener)`, `.find(filters)`, and `.getAll()`. The stock `@tanstack/query-persist-client-core` subscription calls `client.getQueryCache()` and `client.getMutationCache()`. A custom persistence integration for this adapter must subscribe through the named accessors and use this adapter’s `hydrate` and `dehydrate`. + +## Mutations + +`useMutation`, `useMutationState`, and `useIsMutating` acquire the client's mutation cache on demand. `getMutationCache(client)` creates a default cache on first use or returns a cache supplied to the constructor. A query-only app can omit the mutation cache implementation. + +Pass `scope: serialScope('orders')` to `useMutation` to run mutations with that ID one at a time within a cache. The scope ID survives dehydration and hydration. The `queryOptions`, `infiniteQueryOptions`, and `mutationOptions` helpers preserve their TypeScript inference and share one JavaScript identity function. diff --git a/packages/react-query-pluggable/oxlint.config.ts b/packages/react-query-pluggable/oxlint.config.ts new file mode 100644 index 00000000000..91da02f7ef4 --- /dev/null +++ b/packages/react-query-pluggable/oxlint.config.ts @@ -0,0 +1,51 @@ +import pluginReact from '@eslint-react/eslint-plugin' +import reactHooks from 'eslint-plugin-react-hooks' +import { defineConfig } from 'oxlint' +import rootConfig from './root.oxlint.config.ts' + +export default defineConfig({ + extends: [rootConfig], + settings: rootConfig.settings, + jsPlugins: [ + // 'react-hooks' is reserved for Oxlint's native plugin, which lacks the React Compiler rules + { name: 'react-hooks-js', specifier: 'eslint-plugin-react-hooks' }, + '@eslint-react/eslint-plugin', + ], + rules: { + ...Object.fromEntries( + Object.entries(reactHooks.configs.flat.recommended.rules).map( + ([name, value]) => [ + name.replace(/^react-hooks\//, 'react-hooks-js/'), + value, + ], + ), + ), + ...pluginReact.configs.recommended.rules, + 'react-hooks-js/exhaustive-deps': 'error', + 'react-hooks-js/unsupported-syntax': 'error', + 'react-hooks-js/incompatible-library': 'error', + '@eslint-react/no-context-provider': 'off', // We need to be React 18 compatible + '@eslint-react/no-use-context': 'off', // We need to be React 18 compatible + // Covered by 'eslint-plugin-react-hooks' + '@eslint-react/error-boundaries': 'off', + '@eslint-react/exhaustive-deps': 'off', + '@eslint-react/globals': 'off', + '@eslint-react/immutability': 'off', + '@eslint-react/purity': 'off', + '@eslint-react/refs': 'off', + '@eslint-react/rules-of-hooks': 'off', + '@eslint-react/set-state-in-effect': 'off', + '@eslint-react/set-state-in-render': 'off', + '@eslint-react/static-components': 'off', + '@eslint-react/unsupported-syntax': 'off', + '@eslint-react/use-memo': 'off', + }, + overrides: [ + { + files: ['**/__tests__/**'], + rules: { + 'typescript/no-unnecessary-condition': 'off', + }, + }, + ], +}) diff --git a/packages/react-query-pluggable/package.json b/packages/react-query-pluggable/package.json new file mode 100644 index 00000000000..e6a08663d84 --- /dev/null +++ b/packages/react-query-pluggable/package.json @@ -0,0 +1,84 @@ +{ + "name": "@tanstack/react-query-pluggable", + "version": "5.108.4", + "description": "Experimental ESM React Query adapter with per-option features and tree-shakable cache operations", + "author": "tannerlinsley", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/TanStack/query.git", + "directory": "packages/react-query-pluggable" + }, + "homepage": "https://tanstack.com/query", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "scripts": { + "clean": "premove ./build ./coverage ./dist-ts ./.cache/test-types", + "compile": "tsc --project tsconfig.json", + "test:oxlint": "oxlint ./src ./tests", + "test:types": "npm-run-all --serial test:types:*", + "test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js --project tsconfig.legacy.json --outDir .cache/test-types/ts57 --tsBuildInfoFile .cache/test-types/ts57.tsbuildinfo", + "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js --project tsconfig.legacy.json --outDir .cache/test-types/ts58 --tsBuildInfoFile .cache/test-types/ts58.tsbuildinfo", + "test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js --project tsconfig.legacy.json --outDir .cache/test-types/ts59 --tsBuildInfoFile .cache/test-types/ts59.tsbuildinfo", + "test:types:tscurrent": "tsc --project tsconfig.json --outDir .cache/test-types/tscurrent --tsBuildInfoFile .cache/test-types/tscurrent.tsbuildinfo", + "test:types:ts70": "node ../../node_modules/typescript70/lib/tsc.js --project tsconfig.legacy.json --outDir .cache/test-types/ts70 --tsBuildInfoFile .cache/test-types/ts70.tsbuildinfo", + "test:types:ts71": "node ../../node_modules/typescript71/lib/tsc.js --project tsconfig.legacy.json --outDir .cache/test-types/ts71 --tsBuildInfoFile .cache/test-types/ts71.tsbuildinfo", + "test:lib": "vitest run --typecheck src/__tests__ && node ../../scripts/test-react-query-compat.mjs", + "test:lib:dev": "vitest --watch src/__tests__", + "test:build": "publint --strict && attw --pack --profile esm-only", + "build": "tsdown --tsconfig tsconfig.prod.json" + }, + "type": "module", + "types": "./build/index.d.ts", + "main": "./build/index.js", + "react-native": "src/index.ts", + "exports": { + ".": { + "@tanstack/custom-condition": "./src/index.ts", + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "sideEffects": false, + "files": [ + "build", + "src", + "!src/__tests__" + ], + "dependencies": { + "@tanstack/query-core": "workspace:*" + }, + "devDependencies": { + "@eslint-react/eslint-plugin": "catalog:", + "@testing-library/react": "catalog:", + "@types/react": "catalog:", + "@types/react-dom": "catalog:", + "eslint-plugin-react-hooks": "catalog:", + "react": "catalog:", + "react-dom": "catalog:", + "typescript": "catalog:" + }, + "peerDependencies": { + "@types/react": "^19", + "react": "^19" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + }, + "nx": { + "targets": { + "test:lib": { + "inputs": [ + "default", + "^production", + "reactQueryCompatibility" + ] + } + } + } +} diff --git a/packages/react-query-pluggable/root.oxlint.config.ts b/packages/react-query-pluggable/root.oxlint.config.ts new file mode 120000 index 00000000000..56565c65534 --- /dev/null +++ b/packages/react-query-pluggable/root.oxlint.config.ts @@ -0,0 +1 @@ +../../oxlint.config.ts \ No newline at end of file diff --git a/packages/react-query-pluggable/root.tsdown.config.js b/packages/react-query-pluggable/root.tsdown.config.js new file mode 120000 index 00000000000..a997d5d337c --- /dev/null +++ b/packages/react-query-pluggable/root.tsdown.config.js @@ -0,0 +1 @@ +../../scripts/getTsdownConfig.js \ No newline at end of file diff --git a/packages/react-query-pluggable/src/HydrationBoundary.tsx b/packages/react-query-pluggable/src/HydrationBoundary.tsx new file mode 100644 index 00000000000..cc55339b646 --- /dev/null +++ b/packages/react-query-pluggable/src/HydrationBoundary.tsx @@ -0,0 +1,137 @@ +'use client' +import * as React from 'react' +import { useQueryClient } from './QueryClientProvider' +import { hydrateQueries } from './runtime/hydration' +import { getQueryCache } from './runtime/queryClient' +import type { DehydratedState, OmitKeyof } from '@tanstack/query-core' +import type { HydrateOptions } from './runtime/hydration' +import type { QueryClient } from './runtime/queryClient' + +/** + * The props accepted by `HydrationBoundary`. + */ +export interface HydrationBoundaryProps { + /** + * The state to hydrate. Pass the result of `dehydrate(queryClient)`. + */ + state: DehydratedState + /** + * Optional. Note: unlike `hydrate`, `mutations` cannot be set here. + */ + options?: OmitKeyof & { + defaultOptions?: OmitKeyof< + Exclude, + 'mutations' + > + } + /** + * The components to render — always rendered unconditionally, not gated on hydration. New queries are + * hydrated into the cache during render; for queries that already exist in the cache, only newer dehydrated + * data is hydrated, and that happens in an effect after commit, so `children` may render briefly before it + * lands. + */ + children?: React.ReactNode + /** + * Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will be used. + */ + queryClient?: QueryClient +} + +/** + * `HydrationBoundary` adds a previously dehydrated state into the `queryClient` that would be returned by + * `useQueryClient()`. If the client already contains data, the new queries will be intelligently merged based on + * update timestamp. + * + * Note: Only `queries` can be dehydrated with an `HydrationBoundary`. + * @param props - The dehydrated `state` to hydrate, the hydrate `options`, an optional custom + * `queryClient`, and the `children` to render. + * @returns The provided `children`, rendered unconditionally. New queries in `state` are hydrated into the + * cache during render; for queries already in the cache, only newer dehydrated data is hydrated, in an effect + * after commit. + * @example + * ```tsx + * import { HydrationBoundary } from '@tanstack/react-query-pluggable' + * + * function App() { + * return ... + * } + * ``` + * @example + * Server-side prefetch handed off to the client via `dehydrate`: + * ```tsx + * import { HydrationBoundary, dehydrate, noop, fetchQuery } from '@tanstack/react-query-pluggable' + * + * async function ServerComponent() { + * const queryClient = getQueryClient() + * + * await fetchQuery(queryClient, { + * queryKey: ['posts'], + * queryFn: fetchPosts, + * }) + * .catch(noop) + * + * return ( + * + * + * + * ) + * } + * ``` + */ +export const HydrationBoundary = ({ + children, + options = {}, + state, + queryClient, +}: HydrationBoundaryProps) => { + const client = useQueryClient(queryClient) + + const optionsRef = React.useRef(options) + React.useEffect(() => { + optionsRef.current = options + }) + + // Hydrate new queries during render so children can read their data. + // Hydrate existing queries after commit so an aborted transition cannot update them. + const hydrationQueue: DehydratedState['queries'] | undefined = + React.useMemo(() => { + const queryCache = getQueryCache(client) + + const newQueries: DehydratedState['queries'] = [] + const existingQueries: DehydratedState['queries'] = [] + for (const dehydratedQuery of state.queries) { + const existingQuery = queryCache.get(dehydratedQuery.queryHash) + + if (!existingQuery) { + newQueries.push(dehydratedQuery) + continue + } + + const hydrationIsNewer = + dehydratedQuery.state.dataUpdatedAt > + existingQuery.state.dataUpdatedAt || + (dehydratedQuery.promise && + existingQuery.state.status !== 'pending' && + existingQuery.state.fetchStatus !== 'fetching' && + dehydratedQuery.dehydratedAt > existingQuery.state.dataUpdatedAt) + + if (hydrationIsNewer) { + existingQueries.push(dehydratedQuery) + } + } + + if (newQueries.length > 0) { + // oxlint-disable-next-line react-hooks-js/refs -- new queries are hydrated during render on purpose, and 'options' is read through a ref so that a new 'options' object does not rerun this memo + hydrateQueries(client, newQueries, optionsRef.current) + } + return existingQueries.length > 0 ? existingQueries : undefined + }, [client, state]) + + React.useEffect(() => { + if (hydrationQueue) { + hydrateQueries(client, hydrationQueue, optionsRef.current) + } + }, [client, hydrationQueue]) + + return children as React.ReactElement +} diff --git a/packages/react-query-pluggable/src/IsRestoringProvider.ts b/packages/react-query-pluggable/src/IsRestoringProvider.ts new file mode 100644 index 00000000000..abb353406a6 --- /dev/null +++ b/packages/react-query-pluggable/src/IsRestoringProvider.ts @@ -0,0 +1,18 @@ +'use client' +import * as React from 'react' + +const IsRestoringContext = React.createContext(false) + +/** + * If you are using `PersistQueryClientProvider`, you can also use the `useIsRestoring` hook alongside it to + * check if a restore is currently in progress. `useQuery` and friends also check this internally to avoid + * race conditions between the restore and mounting queries. + * @returns `true` while a persisted client is being restored, `false` otherwise. + */ +export const useIsRestoring = () => React.useContext(IsRestoringContext) + +/** + * The Provider that `PersistQueryClientProvider` uses to signal whether a persisted client is currently + * being restored, read by `useIsRestoring`. + */ +export const IsRestoringProvider = IsRestoringContext.Provider diff --git a/packages/react-query-pluggable/src/QueryClientProvider.tsx b/packages/react-query-pluggable/src/QueryClientProvider.tsx new file mode 100644 index 00000000000..3e3f822d84d --- /dev/null +++ b/packages/react-query-pluggable/src/QueryClientProvider.tsx @@ -0,0 +1,85 @@ +'use client' +import * as React from 'react' +import { mountQueryClient, unmountQueryClient } from './runtime/queryClient' +import type { QueryClient } from './runtime/queryClient' + +/** + * The context that `useQueryClient` reads from. `QueryClientProvider` is the normal way to set it. + */ +export const QueryClientContext = React.createContext( + undefined, +) + +/** + * The `useQueryClient` hook returns the current `QueryClient` instance. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns The current `QueryClient` instance. + * @throws {Error} If no `queryClient` argument is passed and no `QueryClientProvider` is found in the + * component tree. + */ +export const useQueryClient = (queryClient?: QueryClient) => { + const client = React.useContext(QueryClientContext) + + if (queryClient) { + return queryClient + } + + if (!client) { + throw new Error('No QueryClient set, use QueryClientProvider to set one') + } + + return client +} + +/** + * The props accepted by `QueryClientProvider`. + */ +export type QueryClientProviderProps = { + /** + * **Required** + * + * The `QueryClient` instance to provide. + */ + client: QueryClient + /** + * The components that get access to the provided `QueryClient`. + */ + children?: React.ReactNode +} + +/** + * Use the `QueryClientProvider` component to connect and provide a `QueryClient` to your application. Also + * calls `mountQueryClient(client)`/`unmountQueryClient(client)` as this component mounts/unmounts, which subscribes the client to + * focus/online events (resuming any paused mutations and refetching as needed when the app regains focus or + * comes back online). + * @param props - The `client` to provide, and the `children` that get access to it. + * @returns The provided `children`, wrapped so they can read the `QueryClient` via `useQueryClient`. + * @example + * ```tsx + * import { QueryClient, QueryClientProvider } from '@tanstack/react-query-pluggable' + * + * const queryClient = new QueryClient() + * + * function App() { + * return ... + * } + * ``` + */ +export const QueryClientProvider = ({ + client, + children, +}: QueryClientProviderProps): React.JSX.Element => { + React.useEffect(() => { + mountQueryClient(client) + return () => { + unmountQueryClient(client) + } + }, [client]) + + return ( + + {children} + + ) +} diff --git a/packages/react-query-pluggable/src/QueryErrorResetBoundary.tsx b/packages/react-query-pluggable/src/QueryErrorResetBoundary.tsx new file mode 100644 index 00000000000..a8835dea36b --- /dev/null +++ b/packages/react-query-pluggable/src/QueryErrorResetBoundary.tsx @@ -0,0 +1,169 @@ +'use client' +import * as React from 'react' + +// CONTEXT + +/** + * Resets any query errors within the boundary, so queries know they can try again. + */ +export type QueryErrorResetFunction = () => void + +/** + * Returns whether the boundary has been reset and not yet cleared. + */ +export type QueryErrorIsResetFunction = () => boolean + +/** + * Clears the reset state, so queries know not to try again until the boundary is reset again. + */ +export type QueryErrorClearResetFunction = () => void + +/** + * The value a `QueryErrorResetBoundary` shares through context, used to reset query errors within + * it and to check whether a reset was requested. + */ +export interface QueryErrorResetBoundaryValue { + /** + * Clears the reset state, so queries know not to try again until the boundary is reset again. + */ + clearReset: QueryErrorClearResetFunction + /** + * Returns whether the boundary has been reset and not yet cleared. + */ + isReset: QueryErrorIsResetFunction + /** + * Resets any query errors within the boundary, so queries know they can try again. + */ + reset: QueryErrorResetFunction +} + +/** + * Creates the value shared through the boundary's context, which tracks whether a reset was + * requested. + * @returns The `clearReset`, `isReset`, and `reset` functions of the boundary. + */ +function createValue(): QueryErrorResetBoundaryValue { + let isReset = false + return { + /** + * Clears the reset state, so queries know not to try again until the boundary is reset again. + */ + clearReset: () => { + isReset = false + }, + /** + * Resets any query errors within the boundary, so queries know they can try again. + */ + reset: () => { + isReset = true + }, + /** + * Returns whether the boundary has been reset and not yet cleared. + * @returns `true` if the boundary has been reset and not yet cleared. + */ + isReset: () => { + return isReset + }, + } +} + +const QueryErrorResetBoundaryContext = React.createContext(createValue()) + +// HOOK + +/** + * This hook will reset any query errors within the closest `QueryErrorResetBoundary`. If there is no boundary + * defined it will reset them globally. + * @returns The boundary's {@link QueryErrorResetBoundaryValue}. + * @example + * ```tsx + * import { ErrorBoundary } from 'react-error-boundary' + * import { useQueryErrorResetBoundary } from '@tanstack/react-query-pluggable' + * + * function App({ children }: { children: React.ReactNode }) { + * const { reset } = useQueryErrorResetBoundary() + * + * return ( + * ( + *
    + * There was an error! + * + *
    + * )} + * > + * {children} + *
    + * ) + * } + * ``` + */ +export const useQueryErrorResetBoundary = () => + React.useContext(QueryErrorResetBoundaryContext) + +// COMPONENT + +/** + * A render-prop function usable as `children` on `QueryErrorResetBoundary`. + * @param value - The boundary's {@link QueryErrorResetBoundaryValue}. + * @returns The children to render. + */ +export type QueryErrorResetBoundaryFunction = ( + value: QueryErrorResetBoundaryValue, +) => React.ReactNode + +/** + * The props accepted by `QueryErrorResetBoundary`. + */ +export interface QueryErrorResetBoundaryProps { + /** + * Either a plain node, or a function that receives the boundary's {@link QueryErrorResetBoundaryValue} and + * returns a node. + */ + children: QueryErrorResetBoundaryFunction | React.ReactNode +} + +/** + * When using `suspense` or `throwOnError` in your queries, you need a way to let queries know that you want to + * try again when re-rendering after some error occurred. With the `QueryErrorResetBoundary` component you can + * reset any query errors within the boundaries of the component. + * @param props - The `children` to render. + * @returns The `children`, rendered as-is, or called with the boundary's {@link QueryErrorResetBoundaryValue} + * if `children` is a function. + * @example + * ```tsx + * import { ErrorBoundary } from 'react-error-boundary' + * import { QueryErrorResetBoundary } from '@tanstack/react-query-pluggable' + * + * function App() { + * return ( + * + * {({ reset }) => ( + * ( + *
    + * There was an error! + * + *
    + * )} + * > + * + *
    + * )} + *
    + * ) + * } + * ``` + */ +export const QueryErrorResetBoundary = ({ + children, +}: QueryErrorResetBoundaryProps) => { + const [value] = React.useState(() => createValue()) + return ( + + {typeof children === 'function' ? children(value) : children} + + ) +} diff --git a/packages/react-query-pluggable/src/__tests__/cacheOperations.test.ts b/packages/react-query-pluggable/src/__tests__/cacheOperations.test.ts new file mode 100644 index 00000000000..2c37ab62532 --- /dev/null +++ b/packages/react-query-pluggable/src/__tests__/cacheOperations.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it } from 'vitest' +import { + QueryClient, + getQueriesData, + invalidateQueries, + removeQueries, + setQueriesData, +} from '..' +import { + getQueryData, + getQueryState, + setQueryData, +} from '../runtime/queryClient' + +describe('cache operations', () => { + it('applies imported cache operations to the supplied client', async () => { + const client = new QueryClient() + const otherClient = new QueryClient() + const filters = { queryKey: ['posts'] } + setQueryData(client, ['posts', 1], 2) + setQueryData(client, ['posts', 2], 3) + setQueryData(otherClient, ['posts', 1], 10) + + setQueriesData(client, filters, (count = 0) => count * 2) + expect(getQueriesData(client, filters)).toStrictEqual([ + [['posts', 1], 4], + [['posts', 2], 6], + ]) + await invalidateQueries(client, { ...filters, refetchType: 'none' }) + expect(getQueryState(client, ['posts', 1])?.isInvalidated).toBe(true) + removeQueries(client, filters) + expect(getQueriesData(client, filters)).toStrictEqual([]) + expect(getQueryData(otherClient, ['posts', 1])).toBe(10) + }) +}) diff --git a/packages/react-query-pluggable/src/__tests__/fetchInfiniteQuery.test.ts b/packages/react-query-pluggable/src/__tests__/fetchInfiniteQuery.test.ts new file mode 100644 index 00000000000..c21430a261e --- /dev/null +++ b/packages/react-query-pluggable/src/__tests__/fetchInfiniteQuery.test.ts @@ -0,0 +1,53 @@ +import { describe, expect, expectTypeOf, it, vi } from 'vitest' +import { + QueryClient, + dehydrate, + fetchInfiniteQuery, + hydrate, + refetchQueries, +} from '..' +import { + clearQueryClient, + getQueryData, + setQueryDefaults, +} from '../runtime/queryClient' +import type { InfiniteData } from '..' + +describe('fetchInfiniteQuery', () => { + it('refetches hydrated pages before any observer subscribes', async () => { + const server = new QueryClient() + const client = new QueryClient() + const queryKey = ['pages'] + const fetchPage = vi.fn<(context: { pageParam?: unknown }) => number>( + ({ pageParam }) => (typeof pageParam === 'number' ? pageParam : -1), + ) + const options = { + queryKey, + queryFn: fetchPage, + initialPageParam: 0, + getNextPageParam: (lastPage: number) => lastPage + 1, + pages: 2, + } + + const promise = fetchInfiniteQuery(server, options) + expectTypeOf(promise).toEqualTypeOf>>() + expect( + fetchPage.mock.calls.map(([context]) => context.pageParam), + ).toStrictEqual([0]) + await promise + + setQueryDefaults(client, queryKey, options) + hydrate(client, dehydrate(server)) + fetchPage.mockClear() + await refetchQueries(client, { queryKey }) + expect( + fetchPage.mock.calls.map(([context]) => context.pageParam), + ).toStrictEqual([0, 1]) + expect(getQueryData(client, queryKey)).toStrictEqual({ + pages: [0, 1], + pageParams: [0, 1], + }) + clearQueryClient(client) + clearQueryClient(server) + }) +}) diff --git a/packages/react-query-pluggable/src/__tests__/getMutationCache.test.ts b/packages/react-query-pluggable/src/__tests__/getMutationCache.test.ts new file mode 100644 index 00000000000..386ebc48fbc --- /dev/null +++ b/packages/react-query-pluggable/src/__tests__/getMutationCache.test.ts @@ -0,0 +1,71 @@ +import { describe, expect, it, vi } from 'vitest' +import { + MutationCache, + MutationObserver, + QueryClient, + dehydrate, + getMutationCache, + hydrate, +} from '..' +import { + clearQueryClient, + getQueryData, + isMutating, + mutationCacheKey, + resumePausedMutations, + setQueryData, +} from '../runtime/queryClient' + +describe('getMutationCache', () => { + it('keeps query-only hydration, resume and clear free of mutation caches', async () => { + const server = new QueryClient() + const client = new QueryClient() + setQueryData(server, ['books'], ['Dune']) + hydrate(client, dehydrate(server)) + + expect(getQueryData(client, ['books'])).toStrictEqual(['Dune']) + expect(isMutating(client)).toBe(0) + await expect(resumePausedMutations(client)).resolves.toStrictEqual([]) + clearQueryClient(client) + expect(getQueryData(client, ['books'])).toBeUndefined() + expect(server[mutationCacheKey]).toBeUndefined() + expect(client[mutationCacheKey]).toBeUndefined() + }) + + it('creates a stable cache per client and reuses it across mutations and clear', async () => { + const first = new QueryClient() + const second = new QueryClient() + const cache = getMutationCache(first) + const otherCache = getMutationCache(second) + expect(cache).not.toBe(otherCache) + const mutation = new MutationObserver(first, { + mutationFn: (title: string) => Promise.resolve(title), + }) + + await mutation.mutate('Dune') + expect(cache.getAll().map((entry) => entry.state.data)).toStrictEqual([ + 'Dune', + ]) + expect(otherCache.getAll()).toStrictEqual([]) + clearQueryClient(first) + expect(cache.getAll()).toStrictEqual([]) + expect(getMutationCache(first)).toBe(cache) + }) + + it('uses an injected cache for the first mutation and its callbacks', async () => { + const onSuccess = vi.fn<() => void>() + const cache = new MutationCache({ onSuccess }) + const client = new QueryClient({ mutationCache: cache }) + const mutation = new MutationObserver(client, { + mutationKey: ['save'], + mutationFn: () => Promise.resolve('saved'), + }) + + await mutation.mutate() + expect(onSuccess).toHaveBeenCalledTimes(1) + expect(getMutationCache(client)).toBe(cache) + expect(cache.find({ mutationKey: ['save'] })?.state.data).toBe('saved') + clearQueryClient(client) + expect(cache.getAll()).toStrictEqual([]) + }) +}) diff --git a/packages/react-query-pluggable/src/__tests__/projection.test-d.ts b/packages/react-query-pluggable/src/__tests__/projection.test-d.ts new file mode 100644 index 00000000000..d0c99bd77e5 --- /dev/null +++ b/packages/react-query-pluggable/src/__tests__/projection.test-d.ts @@ -0,0 +1,72 @@ +import { describe, expectTypeOf, it } from 'vitest' +import { + keepPreviousData, + placeholderData, + select, + useInfiniteQuery, + useQuery, + useSuspenseInfiniteQuery, + useSuspenseQuery, +} from '..' +import type { InfiniteData } from '..' + +describe('projection feature types', () => { + const options = { queryKey: ['orders'], queryFn: () => ({ count: 2 }) } + const count = (order: { count: number }) => order.count + + it('infers the output of a typed selector and preserves the query function data', () => { + const result = useQuery({ + ...options, + placeholderData: placeholderData(keepPreviousData), + select: select(count), + }) + expectTypeOf(result.data).toEqualTypeOf() + const suspense = useSuspenseQuery({ + ...options, + select: [ + select, + (order) => { + expectTypeOf(order).toEqualTypeOf<{ count: number }>() + return order.count + }, + ], + }) + expectTypeOf(suspense.data).toEqualTypeOf() + }) + + it('infers cached pages and the page parameter before selection', () => { + const paging = { + ...options, + initialPageParam: 0, + getNextPageParam: () => 1, + } + const regular = useInfiniteQuery({ + ...paging, + select: [ + select, + (data) => { + expectTypeOf(data).toEqualTypeOf< + InfiniteData<{ count: number }, number> + >() + return data.pages.length + }, + ], + }) + const suspense = useSuspenseInfiniteQuery({ + ...paging, + select: [select, (data) => data.pageParams.join(',')], + }) + expectTypeOf(regular.data).toEqualTypeOf() + expectTypeOf(suspense.data).toEqualTypeOf() + }) + + it('requires the feature for observer selectors and placeholders', () => { + expectTypeOf(select(count)).toEqualTypeOf< + readonly [typeof select, typeof count] + >() + // @ts-expect-error Plain selector callbacks do not install the projection feature. + useQuery({ ...options, select: count }) + // @ts-expect-error Plain placeholder data does not install the placeholder feature. + useQuery({ ...options, placeholderData: { count: 1 } }) + }) +}) diff --git a/packages/react-query-pluggable/src/__tests__/projection.test.ts b/packages/react-query-pluggable/src/__tests__/projection.test.ts new file mode 100644 index 00000000000..f4f5f82d34d --- /dev/null +++ b/packages/react-query-pluggable/src/__tests__/projection.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it, vi } from 'vitest' +import { QueryClient, QueryObserver, placeholderData, select } from '..' +import { + getQueryData, + setQueryData, + setQueryDefaults, +} from '../runtime/queryClient' + +describe('projection options', () => { + it('reuses a stable selector and placeholder factory when option pairs are recreated', () => { + const client = new QueryClient() + const placeholder = vi.fn<() => { count: number }>(() => ({ count: 1 })) + const count = vi.fn<(value: { count: number }) => number>( + (value) => value.count, + ) + const options = () => ({ + queryKey: ['count'], + queryFn: () => Promise.resolve({ count: 2 }), + placeholderData: placeholderData(placeholder), + select: select(count), + }) + const observer = new QueryObserver(client, options()) + expect(observer.getCurrentResult()).toMatchObject({ + data: 1, + isPlaceholderData: true, + }) + observer.setOptions(options()) + expect(placeholder).toHaveBeenCalledTimes(1) + expect(count).toHaveBeenCalledTimes(1) + setQueryData(client, ['count'], { count: 2 }) + observer.setOptions(options()) + expect(observer.getCurrentResult()).toMatchObject({ + data: 2, + isPlaceholderData: false, + }) + }) + + it('keeps selection state and errors separate for observers sharing a default', () => { + const client = new QueryClient() + const transform = (value: unknown) => { + if (typeof value !== 'number') throw new TypeError('Expected a number') + return value * 2 + } + setQueryDefaults(client, ['entry'], { select: select(transform) }) + const a = new QueryObserver(client, { + queryKey: ['entry', 'a'], + queryFn: () => 2, + initialData: 2, + }) + const b = new QueryObserver(client, { + queryKey: ['entry', 'b'], + queryFn: () => 'invalid', + initialData: 'invalid', + }) + expect(a.getCurrentResult()).toMatchObject({ status: 'success', data: 4 }) + expect(b.getCurrentResult()).toMatchObject({ + status: 'error', + data: undefined, + error: expect.any(TypeError), + }) + expect(getQueryData(client, ['entry', 'b'])).toBe('invalid') + }) +}) diff --git a/packages/react-query-pluggable/src/__tests__/queryBuilders.test.ts b/packages/react-query-pluggable/src/__tests__/queryBuilders.test.ts new file mode 100644 index 00000000000..a05c4b96446 --- /dev/null +++ b/packages/react-query-pluggable/src/__tests__/queryBuilders.test.ts @@ -0,0 +1,14 @@ +import { describe, expect, it } from 'vitest' +import { query, queryOptions, skipToken, suspenseQuery } from '..' + +describe('query render modes', () => { + it('keeps ordinary query options by reference and scopes Suspense to the consumer', () => { + const options = queryOptions({ queryKey: ['post'], queryFn: () => 'Dune' }) + expect(query(options)).toBe(options) + expect(suspenseQuery(options).renderPolicy).toBeDefined() + expect( + suspenseQuery({ ...options, queryFn: skipToken }).renderPolicy, + ).toBeUndefined() + expect(options).not.toHaveProperty('renderPolicy') + }) +}) diff --git a/packages/react-query-pluggable/src/__tests__/queryModes.test-d.ts b/packages/react-query-pluggable/src/__tests__/queryModes.test-d.ts new file mode 100644 index 00000000000..fe4c6abab49 --- /dev/null +++ b/packages/react-query-pluggable/src/__tests__/queryModes.test-d.ts @@ -0,0 +1,63 @@ +import { describe, expectTypeOf, it } from 'vitest' +import { + infiniteQuery, + query, + select, + skipToken, + suspenseQuery, + useQuery, +} from '..' +import type { InfiniteData } from '..' + +describe('query render modes', () => { + it('infers data for each render mode from the same query', () => { + const options = { queryKey: ['post'], queryFn: () => ({ title: 'Dune' }) } + expectTypeOf(useQuery(query(options)).data).toEqualTypeOf< + { title: string } | undefined + >() + expectTypeOf(useQuery(suspenseQuery(options)).data).toEqualTypeOf<{ + title: string + }>() + const title = useQuery( + suspenseQuery({ ...options, select: [select, (post) => post.title] }), + ) + expectTypeOf(title.data).toEqualTypeOf() + const maybeFetch = Math.random() > 0.5 ? options.queryFn : skipToken + expectTypeOf( + useQuery(suspenseQuery({ ...options, queryFn: maybeFetch })).data, + ).toEqualTypeOf<{ title: string } | undefined>() + // @ts-expect-error Suspense manages whether the query runs. + suspenseQuery({ ...options, enabled: false }) + }) + + it('preserves page data, controls and selection in both infinite modes', () => { + const options = infiniteQuery({ + queryKey: ['pages'], + initialPageParam: 0, + queryFn: ({ pageParam }) => { + expectTypeOf(pageParam).toEqualTypeOf() + return String(pageParam) + }, + getNextPageParam: (_last, pages) => pages.length, + }) + const regular = useQuery(options) + expectTypeOf(regular.data).toEqualTypeOf< + InfiniteData | undefined + >() + expectTypeOf(regular.hasNextPage).toEqualTypeOf() + const suspended = useQuery(suspenseQuery(options)) + expectTypeOf(suspended.data).toEqualTypeOf>() + expectTypeOf(suspended.fetchNextPage).toEqualTypeOf< + typeof regular.fetchNextPage + >() + const selected = useQuery( + suspenseQuery( + infiniteQuery({ + ...options, + select: [select, (pages) => pages.pages.join(',')], + }), + ), + ) + expectTypeOf(selected.data).toEqualTypeOf() + }) +}) diff --git a/packages/react-query-pluggable/src/__tests__/queryModes.test.tsx b/packages/react-query-pluggable/src/__tests__/queryModes.test.tsx new file mode 100644 index 00000000000..1c4db68debc --- /dev/null +++ b/packages/react-query-pluggable/src/__tests__/queryModes.test.tsx @@ -0,0 +1,90 @@ +// @vitest-environment jsdom + +import { fireEvent, render, screen } from '@testing-library/react' +import * as React from 'react' +import { describe, expect, it, vi } from 'vitest' +import { + QueryClient, + QueryClientProvider, + infiniteQuery, + query, + suspenseQuery, + useQuery, +} from '..' +import { setQueryData } from '../runtime/queryClient' + +describe('query render modes', () => { + it('uses the same cached result when a reader starts suspending', () => { + const client = new QueryClient() + const queryFn = vi.fn<() => string>(() => 'fetched post') + const options = query({ queryKey: ['post'], queryFn, staleTime: Infinity }) + setQueryData(client, options.queryKey, 'cached post') + + function Post({ suspend }: { suspend: boolean }) { + const result = useQuery(suspend ? suspenseQuery(options) : options) + return

    {result.data}

    + } + + function App({ suspend }: { suspend: boolean }) { + return ( + + Loading post

    }> + +
    +
    + ) + } + + const view = render() + screen.getByText('cached post') + view.rerender() + screen.getByText('cached post') + expect(queryFn).not.toHaveBeenCalled() + view.unmount() + }) + + it('can switch the mounted hook to a paginated reader and back', async () => { + const client = new QueryClient() + const post = query({ queryKey: ['post'], queryFn: () => 'single post' }) + const pages = infiniteQuery({ + queryKey: ['pages'], + initialPageParam: 1, + queryFn: ({ pageParam }) => 'page ' + pageParam, + getNextPageParam: (_last, allPages) => allPages.length + 1, + }) + + function Reader({ paged }: { paged: boolean }) { + const result = useQuery(paged ? pages : post) + if ('fetchNextPage' in result) { + return ( + <> +

    {result.data?.pages.join(', ')}

    + + + ) + } + return

    {result.data}

    + } + + function App({ paged }: { paged: boolean }) { + return ( + + + + ) + } + + const view = render() + await screen.findByText('single post') + view.rerender() + await screen.findByText('page 1') + fireEvent.click(screen.getByRole('button', { name: 'Next page' })) + await screen.findByText('page 1, page 2') + view.rerender() + await screen.findByText('single post') + expect(screen.queryAllByRole('button')).toHaveLength(0) + view.unmount() + }) +}) diff --git a/packages/react-query-pluggable/src/__tests__/refetchInterval.test-d.ts b/packages/react-query-pluggable/src/__tests__/refetchInterval.test-d.ts new file mode 100644 index 00000000000..cbb12bed457 --- /dev/null +++ b/packages/react-query-pluggable/src/__tests__/refetchInterval.test-d.ts @@ -0,0 +1,58 @@ +import { describe, expectTypeOf, it } from 'vitest' +import { + refetchInterval, + select, + useInfiniteQuery, + useQuery, + useSuspenseInfiniteQuery, + useSuspenseQuery, +} from '..' +import type { InfiniteData } from '..' + +describe('refetchInterval types', () => { + it('infers cached data in polling callbacks for regular and suspense hooks', () => { + const options = { queryKey: ['book'], queryFn: () => 'Dune' } + useQuery({ + ...options, + select: [select, (book) => book.length], + refetchInterval: (query) => { + expectTypeOf(query.state.data).toEqualTypeOf() + return refetchInterval(query.state.data ? false : 3000) + }, + }) + useSuspenseQuery({ + ...options, + refetchInterval: (query) => { + expectTypeOf(query.state.data).toEqualTypeOf() + return undefined + }, + }) + }) + + it('infers cached pages in both infinite query hooks', () => { + const options = { + queryKey: ['list'], + initialPageParam: 1, + queryFn: () => 'Dune', + getNextPageParam: () => 2, + } + useInfiniteQuery({ + ...options, + refetchInterval: (query) => { + expectTypeOf(query.state.data).toEqualTypeOf< + InfiniteData | undefined + >() + return refetchInterval(3000) + }, + }) + useSuspenseInfiniteQuery({ + ...options, + refetchInterval: (query) => { + expectTypeOf(query.state.data).toEqualTypeOf< + InfiniteData | undefined + >() + return refetchInterval(3000) + }, + }) + }) +}) diff --git a/packages/react-query-pluggable/src/__tests__/refetchInterval.test.ts b/packages/react-query-pluggable/src/__tests__/refetchInterval.test.ts new file mode 100644 index 00000000000..7941a7e0480 --- /dev/null +++ b/packages/react-query-pluggable/src/__tests__/refetchInterval.test.ts @@ -0,0 +1,152 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + MutationObserver, + QueryClient, + QueryObserver, + environmentManager, + fetchInfiniteQuery, + focusManager, + refetchInterval, +} from '..' + +const wasServer = environmentManager.isServer() + +describe('refetchInterval', () => { + beforeEach(() => { + vi.useFakeTimers() + environmentManager.setIsServer(() => false) + focusManager.setFocused(true) + }) + + afterEach(() => { + focusManager.setFocused(undefined) + environmentManager.setIsServer(() => wasServer) + vi.useRealTimers() + }) + + it('keeps the timer cadence on rerender and stops on option removal or unsubscribe', async () => { + const queryFn = vi.fn<() => number>(() => 1) + const options = { + queryKey: ['orders'], + queryFn, + initialData: 1, + staleTime: Infinity, + } + const observer = new QueryObserver(new QueryClient(), { + ...options, + refetchInterval: refetchInterval(100), + }) + const unsubscribe = observer.subscribe(() => {}) + await vi.advanceTimersByTimeAsync(90) + observer.setOptions({ ...options, refetchInterval: refetchInterval(100) }) + await vi.advanceTimersByTimeAsync(10) + expect(queryFn).toHaveBeenCalledTimes(1) + + observer.setOptions({ ...options, refetchInterval: refetchInterval(50) }) + await vi.advanceTimersByTimeAsync(50) + expect(queryFn).toHaveBeenCalledTimes(2) + observer.setOptions(options) + await vi.advanceTimersByTimeAsync(100) + expect(queryFn).toHaveBeenCalledTimes(2) + + observer.setOptions({ ...options, refetchInterval: refetchInterval(50) }) + unsubscribe() + await vi.advanceTimersByTimeAsync(100) + expect(queryFn).toHaveBeenCalledTimes(2) + }) + + it('respects data-dependent intervals, background changes and disabled observers', async () => { + const queryFn = vi.fn<() => number>(() => 2) + const options = { + queryKey: ['orders'], + queryFn, + initialData: 1, + staleTime: Infinity, + } + const client = new QueryClient() + const observer = new QueryObserver(client, { + ...options, + refetchInterval: (query) => + refetchInterval(query.state.data === 1 ? 100 : false), + }) + const unsubscribe = observer.subscribe(() => {}) + focusManager.setFocused(false) + await vi.advanceTimersByTimeAsync(100) + expect(queryFn).not.toHaveBeenCalled() + observer.setOptions({ + ...observer.options, + refetchIntervalInBackground: true, + }) + await vi.advanceTimersByTimeAsync(300) + expect(queryFn).toHaveBeenCalledTimes(1) + observer.setOptions({ + ...observer.options, + enabled: false, + refetchInterval: refetchInterval(100), + }) + await vi.advanceTimersByTimeAsync(100) + expect(queryFn).toHaveBeenCalledTimes(1) + unsubscribe() + }) + + it('shares a default polling option without sharing its timers', async () => { + const client = new QueryClient({ + defaultOptions: { + queries: { refetchInterval: refetchInterval(60), staleTime: Infinity }, + }, + }) + const first = vi.fn<() => number>(() => 1) + const second = vi.fn<() => number>(() => 2) + const a = new QueryObserver(client, { + queryKey: ['a'], + queryFn: first, + initialData: 1, + }) + const b = new QueryObserver(client, { + queryKey: ['b'], + queryFn: second, + initialData: 2, + }) + const unsubscribeA = a.subscribe(() => {}) + const unsubscribeB = b.subscribe(() => {}) + await vi.advanceTimersByTimeAsync(60) + unsubscribeA() + await vi.advanceTimersByTimeAsync(60) + expect(first).toHaveBeenCalledTimes(1) + expect(second).toHaveBeenCalledTimes(2) + unsubscribeB() + }) + + it('keeps server rendering free of polling timers', async () => { + environmentManager.setIsServer(() => true) + const queryFn = vi.fn<() => number>(() => 1) + const observer = new QueryObserver(new QueryClient(), { + queryKey: ['orders'], + queryFn, + initialData: 1, + staleTime: Infinity, + refetchInterval: refetchInterval(100), + }) + const unsubscribe = observer.subscribe(() => {}) + await vi.advanceTimersByTimeAsync(500) + expect(queryFn).not.toHaveBeenCalled() + unsubscribe() + }) + + it('supports mutations and infinite queries on a default client', async () => { + const client = new QueryClient() + const mutation = new MutationObserver(client, { + mutationFn: () => Promise.resolve(42), + }) + await expect(mutation.mutate()).resolves.toBe(42) + await expect( + fetchInfiniteQuery(client, { + queryKey: ['pages'], + initialPageParam: 1, + pages: 2, + queryFn: ({ pageParam }) => pageParam, + getNextPageParam: (page) => page + 1, + }), + ).resolves.toStrictEqual({ pages: [1, 2], pageParams: [1, 2] }) + }) +}) diff --git a/packages/react-query-pluggable/src/__tests__/serialScope.test.ts b/packages/react-query-pluggable/src/__tests__/serialScope.test.ts new file mode 100644 index 00000000000..9eadfa5b8b3 --- /dev/null +++ b/packages/react-query-pluggable/src/__tests__/serialScope.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, it } from 'vitest' +import { + MutationObserver, + QueryClient, + dehydrate, + hydrate, + onlineManager, + serialScope, +} from '..' +import { clearQueryClient, resumePausedMutations } from '../runtime/queryClient' + +describe('serialScope', () => { + it('restores the queue from JSON and resumes its mutations in order', async () => { + const source = new QueryClient() + const started = Promise.withResolvers() + const release = Promise.withResolvers() + const events: Array = [] + const target = new QueryClient({ + defaultOptions: { + mutations: { + mutationFn: async (value) => { + events.push(`start ${value}`) + if (value === 1) { + started.resolve() + await release.promise + } + events.push(`finish ${value}`) + }, + }, + }, + }) + const wasOnline = onlineManager.isOnline() + try { + onlineManager.setOnline(false) + const observer = new MutationObserver(source, { + scope: serialScope('orders'), + mutationFn: (value: number) => Promise.resolve(value), + }) + const first = observer.mutate(1) + const second = observer.mutate(2) + const snapshot = JSON.parse(JSON.stringify(dehydrate(source))) + expect( + snapshot.mutations.map((m: { scope: unknown }) => m.scope), + ).toStrictEqual([{ id: 'orders' }, { id: 'orders' }]) + + hydrate(target, snapshot) + onlineManager.setOnline(true) + const resumed = resumePausedMutations(target) + await started.promise + expect(events).toStrictEqual(['start 1']) + release.resolve() + await resumed + expect(events).toStrictEqual([ + 'start 1', + 'finish 1', + 'start 2', + 'finish 2', + ]) + await resumePausedMutations(source) + await Promise.all([first, second]) + } finally { + release.resolve() + onlineManager.setOnline(wasOnline) + clearQueryClient(source) + clearQueryClient(target) + } + }) +}) diff --git a/packages/react-query-pluggable/src/__tests__/sharedCore.test.ts b/packages/react-query-pluggable/src/__tests__/sharedCore.test.ts new file mode 100644 index 00000000000..87f8b8fcd78 --- /dev/null +++ b/packages/react-query-pluggable/src/__tests__/sharedCore.test.ts @@ -0,0 +1,44 @@ +import { CancelledError, onlineManager } from '@tanstack/query-core' +import { describe, expect, it } from 'vitest' +import { QueryClient, cancelQueries } from '..' +import { + clearQueryClient, + fetchQuery, + getQueryState, + mountQueryClient, + unmountQueryClient, +} from '../runtime/queryClient' + +describe('shared query-core runtime', () => { + it('pauses when core goes offline and resumes when core reconnects', async () => { + const client = new QueryClient() + const wasOnline = onlineManager.isOnline() + mountQueryClient(client) + try { + onlineManager.setOnline(false) + const queryKey = ['connection'] + const pending = fetchQuery(client, { queryKey, queryFn: () => 'online' }) + expect(getQueryState(client, queryKey)?.fetchStatus).toBe('paused') + onlineManager.setOnline(true) + await expect(pending).resolves.toBe('online') + } finally { + unmountQueryClient(client) + onlineManager.setOnline(wasOnline) + clearQueryClient(client) + } + }) + + it('rejects cancelled queries with the core cancellation error', async () => { + const client = new QueryClient() + const queryKey = ['cancel'] + const pending = fetchQuery(client, { + queryKey, + queryFn: () => new Promise(() => {}), + }) + await Promise.all([ + expect(pending).rejects.toBeInstanceOf(CancelledError), + cancelQueries(client, { queryKey }), + ]) + clearQueryClient(client) + }) +}) diff --git a/packages/react-query-pluggable/src/errorBoundaryUtils.ts b/packages/react-query-pluggable/src/errorBoundaryUtils.ts new file mode 100644 index 00000000000..8f5b4573fcc --- /dev/null +++ b/packages/react-query-pluggable/src/errorBoundaryUtils.ts @@ -0,0 +1,103 @@ +'use client' + +import { shouldThrowError } from '@tanstack/query-core/primitives' +import * as React from 'react' +import type { QueryKey, QueryObserverResult } from '@tanstack/query-core' +import type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary' +import type { Query } from './runtime/query' +import type { + DefaultedQueryObserverOptions, + ThrowOnError, +} from './runtime/types' + +/** + * Turns off `retryOnMount` for a query that throws its errors (with `suspense` or `throwOnError`), + * unless the error boundary has been reset, so a remount doesn't retry the failed query before the + * user resets the boundary. Mutates the options. + * @param options - The defaulted query options to adjust. + * @param errorResetBoundary - The value of the nearest `QueryErrorResetBoundary`. + * @param query - The query, used to evaluate a `throwOnError` function against its error. + */ +export const ensurePreventErrorBoundaryRetry = < + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey extends QueryKey, +>( + options: DefaultedQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + errorResetBoundary: QueryErrorResetBoundaryValue, + query: Query | undefined, +) => { + const throwOnError = + query?.state.status === 'error' && + typeof options.throwOnError === 'function' + ? shouldThrowError(options.throwOnError, [ + query.state.error as TError, + query, + ]) + : options.throwOnError + + if (options.suspense || throwOnError) { + // Prevent retrying failed query if the error boundary has not been reset yet + if (!errorResetBoundary.isReset()) { + options.retryOnMount = false + } + } +} + +/** + * Clears the reset state of the error boundary after the component mounts, so later errors are + * thrown to the boundary again. + * @param errorResetBoundary - The value of the nearest `QueryErrorResetBoundary`. + */ +export const useClearResetErrorBoundary = ( + errorResetBoundary: QueryErrorResetBoundaryValue, +) => { + React.useEffect(() => { + errorResetBoundary.clearReset() + }, [errorResetBoundary]) +} + +/** + * Checks whether the query error should be thrown to the nearest error boundary: the query errored + * and isn't fetching, the boundary hasn't been reset, and either `suspense` is enabled with no data + * or `throwOnError` says so. + * @param params - The observer `result`, the `errorResetBoundary`, the `throwOnError` option, the + * `query`, and the `suspense` option. + * @returns `true` if the error should be thrown. + */ +export const getHasError = < + TData, + TError, + TQueryFnData, + TQueryData, + TQueryKey extends QueryKey, +>({ + result, + errorResetBoundary, + throwOnError, + query, + suspense, +}: { + result: QueryObserverResult + errorResetBoundary: QueryErrorResetBoundaryValue + throwOnError: ThrowOnError + query: Query | undefined + suspense: boolean | undefined +}) => { + return ( + result.isError && + !errorResetBoundary.isReset() && + !result.isFetching && + query && + ((suspense && result.data === undefined) || + shouldThrowError(throwOnError, [result.error, query])) + ) +} diff --git a/packages/react-query-pluggable/src/index.ts b/packages/react-query-pluggable/src/index.ts new file mode 100644 index 00000000000..d8addd25e16 --- /dev/null +++ b/packages/react-query-pluggable/src/index.ts @@ -0,0 +1,284 @@ +/* istanbul ignore file */ + +// Public cache and observer API +export { + focusManager, + environmentManager, + onlineManager, + CancelledError, + timeoutManager, + hashKey, + noop, + partialMatchKey, + replaceEqualDeep, + shouldThrowError, + defaultQueryFn, + skipToken, +} from '@tanstack/query-core/primitives' +export type { + FocusManager, + OnlineManager, + TimeoutManager, + ManagedTimerId, + TimeoutCallback, + TimeoutProvider, + DefaultQueryFn, + SkipToken, + Updater, +} from '@tanstack/query-core/primitives' +export { + defaultShouldDehydrateMutation, + defaultShouldDehydrateQuery, + dehydrate, + dehydrateQuery, + hydrate, +} from './runtime/hydration' +export { infiniteQuery } from './infiniteQuery' +export type { InfiniteQueryMode } from './infiniteQuery' +export { fetchInfiniteQuery } from './runtime/fetchInfiniteQuery' +export { InfiniteQueryObserver } from './runtime/infiniteQueryObserver' +export { MutationCache, getMutationCache } from './runtime/mutationCache' +export type { + MutationCacheNotifyEvent, + MutationCacheConfig, +} from './runtime/mutationCache' +export { MutationObserver } from './runtime/mutationObserver' +export { defaultScheduler, notifyManager } from './runtime/notifyManager' +export { QueriesObserver } from './runtime/queriesObserver' +export { QueryCache } from './runtime/queryCache' +export type { + QueryCacheNotifyEvent, + QueryCacheConfig, +} from './runtime/queryCache' +export { + QueryClient, + mountQueryClient, + unmountQueryClient, + isFetching, + isMutating, + getQueryData, + setQueryData, + getQueryState, + fetchQuery, + resumePausedMutations, + getQueryCache, + getDefaultOptions, + setDefaultOptions, + setQueryDefaults, + getQueryDefaults, + setMutationDefaults, + getMutationDefaults, + defaultQueryOptions, + defaultMutationOptions, + clearQueryClient, +} from './runtime/queryClient' +export { + getQueriesData, + setQueriesData, + removeQueries, + resetQueries, + cancelQueries, + invalidateQueries, + refetchQueries, +} from './runtime/cacheOperations' + +export { serialScope } from './runtime/serialScope' +export type { SerialScope } from './runtime/serialScope' +export { select } from './runtime/select' +export { placeholderData } from './runtime/placeholderData' +export type { Select, PlaceholderData } from './runtime/projectionTypes' +export { refetchInterval } from './runtime/refetchInterval' +export type { RefetchInterval } from './runtime/refetchInterval' +export { QueryObserver } from './runtime/queryObserver' + +export { keepPreviousData, matchMutation, matchQuery } from './runtime/utils' +export type { MutationFilters, QueryFilters } from './runtime/utils' +export { streamedQuery } from './runtime/streamedQuery' +export type { DehydrateOptions, HydrateOptions } from './runtime/hydration' +export { Mutation } from './runtime/mutation' +export { Query } from './runtime/query' +export { dataTagSymbol, dataTagErrorSymbol, unsetMarker } from './runtime/types' +export type { + QueryFunction, + StaleTimeFunction, + QueryBooleanOption, + QueryPersister, + QueryFunctionContext, + PlaceholderDataFunction, + QueryOptions, + ThrowOnError, + QueryObserverOptions, + DefaultedQueryObserverOptions, + InfiniteQueryObserverOptions, + DefaultedInfiniteQueryObserverOptions, + QueryExecuteOptions, + InfiniteQueryExecuteOptions, + InvalidateQueryFilters, + RefetchQueryFilters, + MutationFunctionContext, + MutationFunction, + MutationOptions, + MutationObserverOptions, + MutateOptions, + MutateFunctionRest, + MutateFunction, + MutationObserverBaseResult, + MutationObserverIdleResult, + MutationObserverLoadingResult, + MutationObserverErrorResult, + MutationObserverSuccessResult, + MutationObserverResult, + QueryClientConfig, + DefaultOptions, +} from './runtime/types' + +// React Query +export type { + AnyUseBaseQueryOptions, + UseBaseQueryOptions, + UsePrefetchQueryOptions, + UsePrefetchInfiniteQueryOptions, + AnyUseQueryOptions, + UseQueryOptions, + AnyUseSuspenseQueryOptions, + UseSuspenseQueryOptions, + AnyUseInfiniteQueryOptions, + UseInfiniteQueryOptions, + AnyUseSuspenseInfiniteQueryOptions, + UseSuspenseInfiniteQueryOptions, + UseBaseQueryResult, + UseQueryResult, + UseSuspenseQueryResult, + DefinedUseQueryResult, + UseInfiniteQueryResult, + DefinedUseInfiniteQueryResult, + UseSuspenseInfiniteQueryResult, + AnyUseMutationOptions, + UseMutationOptions, + UseMutateFunction, + UseMutateAsyncFunction, + UseBaseMutationResult, + UseMutationResult, +} from './types' +export { useQueries } from './useQueries' +export type { QueriesResults, QueriesOptions } from './useQueries' +export { useQuery } from './useQuery' +export { useSuspenseQuery } from './useSuspenseQuery' +export { suspenseQuery } from './suspenseQuery' +export type { SuspenseQueryMode, SuspenseQueryOptions } from './suspenseQuery' +export { useSuspenseInfiniteQuery } from './useSuspenseInfiniteQuery' +export { useSuspenseQueries } from './useSuspenseQueries' +export type { + SuspenseQueriesResults, + SuspenseQueriesOptions, +} from './useSuspenseQueries' +export { usePrefetchQuery } from './usePrefetchQuery' +export { usePrefetchInfiniteQuery } from './usePrefetchInfiniteQuery' +export { queryOptions, queryOptions as query } from './queryOptions' +export type { + DefinedInitialDataOptions, + UndefinedInitialDataOptions, + UnusedSkipTokenOptions, +} from './queryOptions' +export { infiniteQueryOptions } from './infiniteQueryOptions' +export type { + DefinedInitialDataInfiniteOptions, + UndefinedInitialDataInfiniteOptions, + UnusedSkipTokenInfiniteOptions, +} from './infiniteQueryOptions' +export { + QueryClientContext, + QueryClientProvider, + useQueryClient, +} from './QueryClientProvider' +export type { QueryClientProviderProps } from './QueryClientProvider' +export type { QueryErrorResetBoundaryProps } from './QueryErrorResetBoundary' +export { HydrationBoundary } from './HydrationBoundary' +export type { HydrationBoundaryProps } from './HydrationBoundary' +export type { + QueryErrorClearResetFunction, + QueryErrorIsResetFunction, + QueryErrorResetBoundaryFunction, + QueryErrorResetFunction, +} from './QueryErrorResetBoundary' +export { + QueryErrorResetBoundary, + useQueryErrorResetBoundary, +} from './QueryErrorResetBoundary' +export { useIsFetching } from './useIsFetching' +export { useIsMutating, useMutationState } from './useMutationState' +export { useMutation } from './useMutation' +export { mutationOptions } from './mutationOptions' +export { useInfiniteQuery } from './useInfiniteQuery' +export { useIsRestoring, IsRestoringProvider } from './IsRestoringProvider' + +export type { + QueryObserverResultReader, + DehydratedState, + MutationState, + QueriesObserverOptions, + QueriesObserverResultReader, + QueryState, + NonUndefinedGuard, + DistributiveOmit, + OmitKeyof, + Override, + Register, + DefaultError, + QueryKey, + UnsetMarker, + AnyDataTag, + DataTag, + QueryKeyWithDataTag, + InferDataFromTag, + InferErrorFromTag, + StaleTime, + InitialDataFunction, + QueriesPlaceholderDataFunction, + EqualityFn, + CacheKeyHashFunction, + CacheKeyConfig, + GetPreviousPageParamFunction, + GetNextPageParamFunction, + InfiniteData, + QueryMeta, + NetworkMode, + NotifyOnChangeProps, + InitialPageParam, + InfiniteQueryPageParamsOptions, + WithRequired, + ResultOptions, + RefetchOptions, + InvalidateOptions, + ResetOptions, + FetchNextPageOptions, + FetchPreviousPageOptions, + QueryStatus, + FetchStatus, + QueryObserverBaseResult, + QueryObserverPendingResult, + QueryObserverLoadingResult, + QueryObserverLoadingErrorResult, + QueryObserverRefetchErrorResult, + QueryObserverSuccessResult, + QueryObserverPlaceholderResult, + DefinedQueryObserverResult, + QueryObserverResult, + InfiniteQueryObserverBaseResult, + InfiniteQueryObserverPendingResult, + InfiniteQueryObserverLoadingResult, + InfiniteQueryObserverLoadingErrorResult, + InfiniteQueryObserverRefetchErrorResult, + InfiniteQueryObserverSuccessResult, + InfiniteQueryObserverPlaceholderResult, + DefinedInfiniteQueryObserverResult, + InfiniteQueryObserverResult, + MutationKey, + MutationStatus, + MutationScope, + MutationMeta, + CancelOptions, + SetDataOptions, + NotifyEventType, + NotifyEvent, +} from '@tanstack/query-core' diff --git a/packages/react-query-pluggable/src/infiniteQuery.ts b/packages/react-query-pluggable/src/infiniteQuery.ts new file mode 100644 index 00000000000..bef674411f0 --- /dev/null +++ b/packages/react-query-pluggable/src/infiniteQuery.ts @@ -0,0 +1,85 @@ +import { InfiniteQueryObserver } from './runtime/infiniteQueryObserver' +import type { DefaultError, InfiniteData, QueryKey } from '@tanstack/query-core' +import type { + DefinedInitialDataInfiniteOptions, + UnusedSkipTokenInfiniteOptions, +} from './infiniteQueryOptions' +import type { + AnyUseInfiniteQueryOptions, + UseInfiniteQueryOptions, +} from './types' + +/** Identifies options that read pages through an infinite query observer. */ +export interface InfiniteQueryMode { + /** The observer that adds pagination controls to the result. */ + readonly Observer: typeof InfiniteQueryObserver +} + +/** + * Configures a paginated query to read through `useQuery`. + * @param options - The page fetcher, initial page parameter and pagination callbacks. + * @returns The options with their matching observer. + */ +export function infiniteQuery< + TQueryFnData, + TPageParam = unknown, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, +>( + options: DefinedInitialDataInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, +): DefinedInitialDataInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> & + InfiniteQueryMode +export function infiniteQuery< + TQueryFnData, + TPageParam = unknown, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, +>( + options: UnusedSkipTokenInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, +): UnusedSkipTokenInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> & + InfiniteQueryMode +export function infiniteQuery< + TQueryFnData, + TPageParam = unknown, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, +>( + options: UseInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, +): UseInfiniteQueryOptions & + InfiniteQueryMode +export function infiniteQuery(options: AnyUseInfiniteQueryOptions) { + return { ...options, Observer: InfiniteQueryObserver } +} diff --git a/packages/react-query-pluggable/src/infiniteQueryOptions.ts b/packages/react-query-pluggable/src/infiniteQueryOptions.ts new file mode 100644 index 00000000000..3216da8a03a --- /dev/null +++ b/packages/react-query-pluggable/src/infiniteQueryOptions.ts @@ -0,0 +1,305 @@ +import { identity } from './runtime/identity' +import type { + DefaultError, + InfiniteData, + InitialDataFunction, + NonUndefinedGuard, + OmitKeyof, + QueryKey, + QueryKeyWithDataTag, +} from '@tanstack/query-core' +import type { SkipToken } from '@tanstack/query-core/primitives' +import type { UseInfiniteQueryOptions } from './types' + +/** + * The options accepted by the `infiniteQueryOptions` overload selected when `initialData` is omitted, may be + * `undefined`, or is a function that may return `undefined` — `data` may be `undefined` while the query is + * `pending`. + * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData`, + * the shape of all fetched pages plus their page params. + * @template TQueryKey - The type of your `queryKey`. + * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page. + */ +export type UndefinedInitialDataInfiniteOptions< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> = UseInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> & { + /** + * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been + * created or cached yet). If set to a function, the function will be called **once** during the shared/root + * query initialization, and be expected to synchronously return the initial data. Initial data is + * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the + * cache. + */ + initialData?: + | undefined + | NonUndefinedGuard> + | InitialDataFunction< + NonUndefinedGuard> + > +} + +/** + * The options accepted by the `infiniteQueryOptions` overload selected when `queryFn` is not `skipToken` and + * `initialData` is omitted, may be `undefined`, or is a function that may return `undefined` — same as + * {@link UndefinedInitialDataInfiniteOptions}, but `queryFn` may not be `skipToken`. + * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData`, + * the shape of all fetched pages plus their page params. + * @template TQueryKey - The type of your `queryKey`. + * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page. + */ +export interface UnusedSkipTokenInfiniteOptions< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> extends OmitKeyof< + UseInfiniteQueryOptions, + 'queryFn' +> { + /** The query function or the configured client default. */ + queryFn: Exclude< + UseInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >['queryFn'], + SkipToken + > +} + +/** + * The options accepted by the `infiniteQueryOptions` overload selected when `initialData` is known to be + * defined — `data` is never `undefined` (unless a `select` changes `TData` to include `undefined`). + * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData`, + * the shape of all fetched pages plus their page params. + * @template TQueryKey - The type of your `queryKey`. + * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page. + */ +export type DefinedInitialDataInfiniteOptions< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> = UseInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> & { + /** + * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been + * created or cached yet). If set to a function, the function will be called **once** during the shared/root + * query initialization, and be expected to synchronously return the initial data. Initial data is + * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the + * cache. + */ + initialData: + | NonUndefinedGuard> + | (() => NonUndefinedGuard>) +} + +type InfiniteQueryOptionsFn = { + /** + * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. + * These options can be shared across hooks and imperative APIs such as `fetchInfiniteQuery(client, options)`. + * `options.queryKey` is required and is the query key to generate options for. + * + * This overload is selected when `initialData` is known to be defined. + * @param options - The {@link DefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`, with `initialData` known to be defined. + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + * @remarks See {@link useInfiniteQuery} for examples that fetch further pages, from a button click or + * automatically as the user scrolls. + * @see {@link useInfiniteQuery} to run an infinite query with these options. + * @example + * ```tsx + * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query-pluggable' + * + * export const projectsOptions = infiniteQueryOptions({ + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * initialData: { pages: [], pageParams: [] }, + * }) + * + * function Projects() { + * // `data` is never `undefined`, thanks to `initialData` — even if a refetch fails, so the + * // list stays visible alongside the error. + * const { data, isError, error } = useInfiniteQuery(projectsOptions) + * + * return ( + *
    + * {isError ? Error: {error.message} : null} + *
      + * {data.pages.map((page) => page.projects.map((p) =>
    • {p.name}
    • ))} + *
    + *
    + * ) + * } + * ``` + */ + < + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, + >( + options: DefinedInitialDataInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + ): DefinedInitialDataInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + > & + QueryKeyWithDataTag, TError> + + /** + * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. + * These options can be shared across hooks and imperative APIs such as `fetchInfiniteQuery(client, options)`. + * `options.queryKey` is required and is the query key to generate options for. + * @param options - The {@link UnusedSkipTokenInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`. + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + * @remarks See {@link useInfiniteQuery} for examples that fetch further pages, from a button click or + * automatically as the user scrolls. + * @see {@link useInfiniteQuery} to run an infinite query with these options. + * @example + * A parameterized factory, so the same options object can be reused per `postId`: + * ```tsx + * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query-pluggable' + * + * export const commentsOptions = (postId: string) => + * infiniteQueryOptions({ + * queryKey: ['post', postId, 'comments'], + * queryFn: ({ pageParam }) => fetchComments(postId, pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * function Comments({ postId }: { postId: string }) { + * const { data, isPending, isError, error } = useInfiniteQuery(commentsOptions(postId)) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return ( + *
      + * {data.pages.map((page) => page.comments.map((c) =>
    • {c.text}
    • ))} + *
    + * ) + * } + * ``` + */ + < + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, + >( + options: UnusedSkipTokenInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + ): UnusedSkipTokenInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + > & + QueryKeyWithDataTag, TError> + + /** + * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. + * These options can be shared across hooks and imperative APIs such as `fetchInfiniteQuery(client, options)`. + * `options.queryKey` is required and is the query key to generate options for. + * @param options - The {@link UndefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`. + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + * @remarks See {@link useInfiniteQuery} for examples that fetch further pages (from a button click or + * automatically as the user scrolls) and that use `skipToken` to disable the query until `postId` is set. + * @see {@link useInfiniteQuery} to run an infinite query with these options. + * @example + * A parameterized factory, so the same options object can be reused per `postId`: + * ```tsx + * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query-pluggable' + * + * export const commentsOptions = (postId: string) => + * infiniteQueryOptions({ + * queryKey: ['post', postId, 'comments'], + * queryFn: ({ pageParam }) => fetchComments(postId, pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * function Comments({ postId }: { postId: string }) { + * const { data, isPending, isError, error } = useInfiniteQuery(commentsOptions(postId)) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return ( + *
      + * {data.pages.map((page) => page.comments.map((c) =>
    • {c.text}
    • ))} + *
    + * ) + * } + * ``` + */ + < + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, + >( + options: UndefinedInitialDataInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + ): UndefinedInitialDataInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + > & + QueryKeyWithDataTag, TError> +} + +/** Preserves infinite query options and tags their key with the inferred pages and error types. */ +export const infiniteQueryOptions: InfiniteQueryOptionsFn = identity diff --git a/packages/react-query-pluggable/src/mutationOptions.ts b/packages/react-query-pluggable/src/mutationOptions.ts new file mode 100644 index 00000000000..91e9ab212fd --- /dev/null +++ b/packages/react-query-pluggable/src/mutationOptions.ts @@ -0,0 +1,89 @@ +import { identity } from './runtime/identity' +import type { DefaultError, WithRequired } from '@tanstack/query-core' +import type { UseMutationOptions } from './types' + +type MutationOptionsFn = { + /** + * You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. A + * `mutationKey` is required on this overload so the mutation can be looked up later, e.g. with + * `useMutationState`. + * @param options - The mutation options to use, identical to what you'd pass to `useMutation`, with a + * required `mutationKey`. + * @returns The same options object, unchanged. + * @see {@link useMutation} to run the mutation these options describe. + * @example + * Looking the mutation up elsewhere via its `mutationKey`, e.g. for a global "saving…" indicator: + * ```tsx + * import { mutationOptions, useMutationState } from '@tanstack/react-query-pluggable' + * + * const createPostOptions = mutationOptions({ + * mutationKey: ['posts', 'create'], + * mutationFn: createPost, + * }) + * + * function SavingIndicator() { + * const isCreatingPost = useMutationState({ + * filters: { mutationKey: createPostOptions.mutationKey, status: 'pending' }, + * }).length > 0 + * + * return isCreatingPost ? Saving… : null + * } + * ``` + */ + < + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, + >( + options: WithRequired< + UseMutationOptions, + 'mutationKey' + >, + ): WithRequired< + UseMutationOptions, + 'mutationKey' + > + + /** + * You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. No + * `mutationKey` is required on this overload — use this when you don't need to target the mutation via a + * `mutationKey` filter later (e.g. with `useMutationState`); it can still be observed through other filters, + * such as `status`. + * @param options - The mutation options to use, identical to what you'd pass to `useMutation`, without a + * `mutationKey`. + * @returns The same options object, unchanged. + * @remarks See the other overload's example for looking a mutation up via `useMutationState`. + * @see {@link useMutation} to run the mutation these options describe. + * @example + * ```tsx + * import { mutationOptions, useMutation } from '@tanstack/react-query-pluggable' + * + * export const createPostOptions = mutationOptions({ + * mutationFn: createPost, + * }) + * + * function CreatePost() { + * const mutation = useMutation(createPostOptions) + * return + * } + * ``` + */ + < + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, + >( + options: Omit< + UseMutationOptions, + 'mutationKey' + >, + ): Omit< + UseMutationOptions, + 'mutationKey' + > +} + +/** Preserves mutation option types when reusing the same options in multiple places. */ +export const mutationOptions: MutationOptionsFn = identity diff --git a/packages/react-query-pluggable/src/queryOptions.ts b/packages/react-query-pluggable/src/queryOptions.ts new file mode 100644 index 00000000000..616e93e043c --- /dev/null +++ b/packages/react-query-pluggable/src/queryOptions.ts @@ -0,0 +1,249 @@ +import { identity } from './runtime/identity' +import type { + DefaultError, + InitialDataFunction, + NonUndefinedGuard, + OmitKeyof, + QueryKey, + QueryKeyWithDataTag, +} from '@tanstack/query-core' +import type { DefaultQueryFn, SkipToken } from '@tanstack/query-core/primitives' +import type { QueryFunction } from './runtime/types' +import type { UseQueryOptions } from './types' + +/** + * The options accepted by the `queryOptions` overload selected when `initialData` is omitted, may be + * `undefined`, or is a function that may return `undefined` — `data` may be `undefined` while the query is + * `pending`. + * @template TQueryFnData - The type your `queryFn` resolves to. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. + * @template TQueryKey - The type of your `queryKey`. + */ +export type UndefinedInitialDataOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = UseQueryOptions & { + /** + * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been + * created or cached yet). If set to a function, the function will be called **once** during the shared/root + * query initialization, and be expected to synchronously return the initial data. Initial data is + * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the + * cache. + */ + initialData?: + | undefined + | InitialDataFunction> + | NonUndefinedGuard +} + +/** + * The options accepted by the `queryOptions` overload selected when `queryFn` is not `skipToken` and + * `initialData` is omitted, may be `undefined`, or is a function that may return `undefined` — same as + * {@link UndefinedInitialDataOptions}, but `queryFn` may not be `skipToken`. + * @template TQueryFnData - The type your `queryFn` resolves to. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. + * @template TQueryKey - The type of your `queryKey`. + */ +export interface UnusedSkipTokenOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> extends OmitKeyof< + UseQueryOptions, + 'queryFn' +> { + /** The query function or the configured client default. */ + queryFn: Exclude< + UseQueryOptions['queryFn'], + SkipToken + > +} + +/** + * The options accepted by the `queryOptions` overload selected when `initialData` is known to be defined — + * `data` is never `undefined` (unless a `select` changes `TData` to include `undefined`). + * @template TQueryFnData - The type your `queryFn` resolves to. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. + * @template TQueryKey - The type of your `queryKey`. + */ +export type DefinedInitialDataOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = Omit, 'queryFn'> & { + /** + * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been + * created or cached yet). If set to a function, the function will be called **once** during the shared/root + * query initialization, and be expected to synchronously return the initial data. Initial data is + * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the + * cache. + */ + initialData: + | NonUndefinedGuard + | (() => NonUndefinedGuard) + queryFn: QueryFunction | DefaultQueryFn +} + +type QueryOptionsFn = { + /** + * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can + * be shared across hooks and imperative APIs such as `fetchQuery`. `options.queryKey` is required and + * is the query key to generate options for. + * + * This overload is selected when `initialData` is known to be defined, so the resulting `data` is never + * `undefined` (unless a `select` changes `TData` to include `undefined`). + * @param options - The {@link DefinedInitialDataOptions} to use — everything you can pass to `useQuery`, with `initialData` known to be defined. + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + * @see {@link useQuery} to run a query with these options. + * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern. + * @example + * ```tsx + * import { queryOptions, useQuery } from '@tanstack/react-query-pluggable' + * + * export const postsOptions = queryOptions({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * initialData: [], + * }) + * + * function Posts() { + * // `data` is `Post[]`, never `undefined`, thanks to `initialData` — even if a refetch fails, + * // so the list stays visible alongside the error. + * const { data, isError, error } = useQuery(postsOptions) + * + * return ( + *
    + * {isError ? Error: {error.message} : null} + *
      + * {data.map((post) =>
    • {post.title}
    • )} + *
    + *
    + * ) + * } + * ``` + */ + < + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + >( + options: DefinedInitialDataOptions, + ): DefinedInitialDataOptions & + QueryKeyWithDataTag + + /** + * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can + * be shared across hooks and imperative APIs such as `fetchQuery`. `options.queryKey` is required and + * is the query key to generate options for. + * @param options - The {@link UnusedSkipTokenOptions} to use — everything you can pass to `useQuery`. + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + * @see {@link useQuery} to run a query with these options. + * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern. + * @example + * A parameterized factory, so the same options object can be reused per `id`: + * ```tsx + * import { queryOptions, useQuery } from '@tanstack/react-query-pluggable' + * + * export const postOptions = (id: string) => + * queryOptions({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * }) + * + * function Post({ id }: { id: string }) { + * const { data, isPending, isError, error } = useQuery(postOptions(id)) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return

    {data.title}

    + * } + * ``` + */ + < + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + >( + options: UnusedSkipTokenOptions, + ): UnusedSkipTokenOptions & + QueryKeyWithDataTag + + /** + * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can + * be shared across hooks and imperative APIs such as `fetchQuery`. `options.queryKey` is required and + * is the query key to generate options for. + * @param options - The {@link UndefinedInitialDataOptions} to use — everything you can pass to `useQuery`. + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + * @remarks This is the only overload that accepts `queryFn: skipToken`, shown below. + * @see {@link useQuery} to run a query with these options. + * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern. + * @example + * A parameterized factory, so the same options object can be reused per `id`: + * ```tsx + * import { queryOptions, useQuery } from '@tanstack/react-query-pluggable' + * + * export const postOptions = (id: string) => + * queryOptions({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * }) + * + * function Post({ id }: { id: string }) { + * const { data, isPending, isError, error } = useQuery(postOptions(id)) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return

    {data.title}

    + * } + * ``` + * @example + * A factory that disables the query, type safe, until `postId` is set: + * ```tsx + * import { queryOptions, skipToken, useQuery } from '@tanstack/react-query-pluggable' + * + * export const postOptions = (postId: number | undefined) => + * queryOptions({ + * queryKey: ['post', postId], + * queryFn: postId != null ? () => fetchPost(postId) : skipToken, + * }) + * + * function Post({ postId }: { postId: number | undefined }) { + * const { data, isLoading, isError, error } = useQuery(postOptions(postId)) + * + * if (postId == null) return 'Select a post' + * if (isLoading) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return

    {data?.title}

    + * } + * ``` + */ + < + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + >( + options: UndefinedInitialDataOptions< + TQueryFnData, + TError, + TData, + TQueryKey + >, + ): UndefinedInitialDataOptions & + QueryKeyWithDataTag +} + +/** Preserves query options and tags their key with the inferred data and error types. */ +export const queryOptions: QueryOptionsFn = identity diff --git a/packages/react-query-pluggable/src/runtime/cacheOperations.ts b/packages/react-query-pluggable/src/runtime/cacheOperations.ts new file mode 100644 index 00000000000..d5eeb9b972a --- /dev/null +++ b/packages/react-query-pluggable/src/runtime/cacheOperations.ts @@ -0,0 +1,283 @@ +import { noop } from '@tanstack/query-core/primitives' +import { notifyManager } from './notifyManager' +import { getQueryCache, setQueryData } from './queryClient' +import type { Updater } from '@tanstack/query-core/primitives' +import type { QueryClient } from './queryClient' +import type { + CancelOptions, + InvalidateOptions, + InvalidateQueryFilters, + QueryKey, + RefetchOptions, + RefetchQueryFilters, + ResetOptions, + SetDataOptions, +} from './types' +import type { QueryFilters } from './utils' + +/** + * Imperative (non-reactive) way to retrieve the cached data of multiple queries at once. + * Only queries matching the given filters are returned; if none match, an empty array is + * returned. + * + * Because the matched queries can hold data of different shapes (e.g. a broad filter can match + * queries with unrelated data types), the `TQueryFnData` generic defaults to `unknown` rather + * than being inferred. Passing a more specific type is a convenience for call sites that know + * every matched query holds the same shape — it is not checked against the actual cache + * contents. + * @param client - The client that owns the query cache. + * @param filters - The filters that select which queries to read. + * @returns An array of query key and data pairs. The data is `undefined` for a query with no cached data. + * @see {@link getQueryData} + * @example + * ```ts + * const data = getQueriesData(queryClient, { queryKey: ['posts'] }) + * ``` + */ +export function getQueriesData< + TQueryFnData = unknown, + TQueryFilters extends QueryFilters = QueryFilters, +>( + client: QueryClient, + filters: TQueryFilters, +): Array<[QueryKey, TQueryFnData | undefined]> { + return getQueryCache(client) + .findAll(filters) + .map(({ queryKey, state }) => { + const data = state.data as TQueryFnData | undefined + return [queryKey, data] + }) +} + +/** + * Synchronous way to immediately update the cached data of multiple queries at once, using + * filters or partial query key matching. Only queries that already exist and match the given + * filters are updated; no new cache entries are created. Internally this calls + * {@link setQueryData} for each matching query. + * @param client - The client that owns the query cache. + * @param filters - The filters that select which existing queries to update. + * @param updater - Either the new data, or a function that receives each matched query's current + * data (which may be `undefined`) and returns the new data. + * @param options - Set `updatedAt` to override the timestamp the written data is recorded with. + * @returns One `[queryKey, data]` tuple per matched query, in the same shape and with the same + * `undefined` case as {@link setQueryData}. + * @example + * ```ts + * setQueriesData(queryClient, { queryKey: ['posts'] }, (oldPosts) => + * oldPosts ? oldPosts.filter((post) => post.id !== deletedId) : oldPosts) + * ``` + */ +export function setQueriesData< + TQueryFnData, + TQueryFilters extends QueryFilters = QueryFilters, +>( + client: QueryClient, + filters: TQueryFilters, + updater: Updater< + NoInfer | undefined, + NoInfer | undefined + >, + options?: SetDataOptions, +): Array<[QueryKey, TQueryFnData | undefined]> { + return notifyManager.batch(() => + getQueryCache(client) + .findAll(filters) + .map(({ queryKey }) => [ + queryKey, + setQueryData(client, queryKey, updater, options), + ]), + ) +} + +/** + * Removes queries from the cache that match the given filters. Unlike + * {@link invalidateQueries} or {@link refetchQueries}, this removes + * matching queries from the cache instead of refetching them. Without filters, every query in + * the cache is removed. + * @param client - The client that owns the query cache. + * @param filters - The filters that select which queries to remove. Without filters, every query + * is removed. + * @example + * ```ts + * removeQueries(queryClient, { queryKey: ['posts'], exact: true }) + * ``` + */ +export function removeQueries( + client: QueryClient, + filters?: QueryFilters, +): void { + const queryCache = getQueryCache(client) + notifyManager.batch(() => { + queryCache.findAll(filters).forEach((query) => { + queryCache.remove(query) + }) + }) +} + +/** + * Resets queries matching the given filters back to their initial state (e.g. any + * `initialData`), notifying subscribers rather than removing them. Active queries among the + * matched set are then refetched, and the returned promise resolves once that refetch settles. + * @param client - The client that owns the query cache. + * @param filters - The filters that select which queries to reset. Without filters, every query + * is reset. + * @param options - Passed to the refetch of the active matched queries, e.g. `cancelRefetch` and + * `throwOnError`. + * @returns A promise that resolves once the refetch of the active matched queries settles. + * @example + * ```ts + * await resetQueries(queryClient, { queryKey: ['posts'], exact: true }) + * ``` + */ +export function resetQueries( + client: QueryClient, + filters?: QueryFilters, + options?: ResetOptions, +): Promise { + const queryCache = getQueryCache(client) + + return notifyManager.batch(() => { + const matched = queryCache.findAll(filters) + const queriesToRefetch = new Set(matched) + matched.forEach((query) => { + query.reset() + }) + return refetchQueries( + client, + { + type: 'active', + predicate: (query) => queriesToRefetch.has(query), + }, + options, + ) + }) +} + +/** + * Cancels outgoing fetches for queries matching the given filters. Most useful when performing + * optimistic updates, since any outgoing refetch that resolves afterwards would otherwise + * overwrite the optimistic update. By default (`revert: true`), a cancelled query's data is + * reverted to its state before the outgoing fetch started. + * + * The returned promise never rejects, even if individual cancellations fail. + * @param client - The client that owns the query cache. + * @param filters - The filters that select which queries to cancel. Without filters, every query + * is cancelled. + * @param cancelOptions - Passed to each matched query's cancellation. `revert` defaults to + * `true`. + * @returns A promise that resolves once every cancellation has settled. + * @example + * ```ts + * await cancelQueries(queryClient, { queryKey: ['posts'], exact: true }) + * ``` + */ +export function cancelQueries( + client: QueryClient, + filters?: QueryFilters, + cancelOptions: CancelOptions = {}, +): Promise { + const defaultedCancelOptions = { revert: true, ...cancelOptions } + + const promises = notifyManager.batch(() => + getQueryCache(client) + .findAll(filters) + .map((query) => query.cancel(defaultedCancelOptions)), + ) + + return Promise.all(promises).then(noop, noop) +} + +/** + * Marks queries matching the given filters as invalidated. Unlike + * {@link removeQueries}, invalidated queries stay in the cache. + * + * Unless `filters.refetchType` is `'none'`, matching queries are then refetched via + * {@link refetchQueries}, using `filters.refetchType` if set, otherwise + * `filters.type`, otherwise `'active'`. + * @param client - The client that owns the query cache. + * @param filters - The filters that select which queries to invalidate, plus `refetchType` to + * control which of them to refetch afterwards. Without filters, every query is invalidated. + * @param options - Passed to {@link refetchQueries}, e.g. `cancelRefetch` and + * `throwOnError`. + * @returns A promise that resolves once the refetch settles, or immediately if `refetchType` is + * `'none'`. + * @example + * ```ts + * await invalidateQueries(queryClient, { queryKey: ['posts'], refetchType: 'active' }) + * ``` + */ +export function invalidateQueries( + client: QueryClient, + filters?: InvalidateQueryFilters, + options?: InvalidateOptions, +): Promise { + return notifyManager.batch(() => { + getQueryCache(client) + .findAll(filters) + .forEach((query) => { + query.invalidate() + }) + + if (filters?.refetchType === 'none') { + return Promise.resolve() + } + return refetchQueries( + client, + { + ...filters, + type: filters?.refetchType ?? filters?.type ?? 'active', + }, + options, + ) + }) +} + +/** + * Refetches queries matching the given filters, regardless of whether they are stale. Without + * filters, every query in the cache is refetched. Queries that are disabled, or static (only + * have observers with a static `staleTime`), are never refetched. + * + * By default (`cancelRefetch: true`), a currently running fetch is cancelled before the new + * one starts. The returned promise does not reject on individual query failures unless + * `throwOnError` is `true`. + * + * Initially paused fetches do not delay the returned promise. Their later errors are handled + * even when `throwOnError` is `true`. + * @param client - The client that owns the query cache. + * @param filters - The filters that select which queries to refetch. Without filters, every query + * in the cache is included. + * @param options - Set `cancelRefetch` to `false` to keep a running fetch instead of cancelling + * it, and `throwOnError` to `true` to reject when a refetch that was not initially paused fails. + * @returns A promise that resolves once all matching refetches that were not initially paused + * have settled. + * @example + * ```ts + * // refetch all active queries partially matching a query key: + * await refetchQueries(queryClient, { queryKey: ['posts'], type: 'active' }) + * ``` + */ +export function refetchQueries( + client: QueryClient, + filters?: RefetchQueryFilters, + options?: RefetchOptions, +): Promise { + const fetchOptions = { + ...options, + cancelRefetch: options?.cancelRefetch ?? true, + } + const promises = notifyManager.batch(() => + getQueryCache(client) + .findAll(filters) + .filter((query) => !query.isDisabled() && !query.isStatic()) + .map((query) => { + let promise = query.fetch(undefined, fetchOptions) + const isPaused = query.state.fetchStatus === 'paused' + if (!fetchOptions.throwOnError || isPaused) { + promise = promise.catch(noop) + } + return isPaused ? Promise.resolve() : promise + }), + ) + + return Promise.all(promises).then(noop) +} diff --git a/packages/react-query-pluggable/src/runtime/fetchInfiniteQuery.ts b/packages/react-query-pluggable/src/runtime/fetchInfiniteQuery.ts new file mode 100644 index 00000000000..4d9b666a424 --- /dev/null +++ b/packages/react-query-pluggable/src/runtime/fetchInfiniteQuery.ts @@ -0,0 +1,105 @@ +import { infiniteFetchOptions } from './infiniteQueryBehavior' +import { fetchQuery } from './queryClient' +import type { QueryClient, WithoutSkipToken } from './queryClient' +import type { + DefaultError, + InfiniteData, + InfiniteQueryExecuteOptions, + QueryKey, +} from './types' + +/** + * Asynchronous method to fetch and cache an infinite query, resolving with an + * {@link InfiniteData} object or throwing with the error. + * + * Requires `initialPageParam` and `getNextPageParam`. Use `pages` to specify how many + * pages to fetch. If you omit `pages`, the client fetches up to the number of cached + * pages, or one page if the cache has no pages. + * If shared infinite query options contain `skipToken` as their `queryFn`, the call skips fetching + * and resolves with existing data or `undefined` on a cache miss. Use {@link getQueryData} + * to read the cache directly. + * @param client - The client that stores the query. + * @param options - The query to fetch and the options that control which pages to fetch. + * @returns A promise that resolves to the {@link InfiniteData}, or to the result of `select` if + * provided. It rejects with the error from the fetch or from `select`. + * @example + * ```ts + * try { + * const data = await fetchInfiniteQuery(queryClient, { + * queryKey, + * queryFn, + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextCursor, + * }) + * console.log(data.pages) + * } catch (error) { + * console.log(error) + * } + * ``` + */ +export function fetchInfiniteQuery< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + client: QueryClient, + options: WithoutSkipToken< + InfiniteQueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + > + >, +): Promise< + Array extends Array> + ? InfiniteData + : TData +> +export function fetchInfiniteQuery< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + client: QueryClient, + options: InfiniteQueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, +): Promise< + | undefined + | (Array extends Array> + ? InfiniteData + : TData) +> +export function fetchInfiniteQuery< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + client: QueryClient, + options: InfiniteQueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, +): Promise< + | undefined + | (Array extends Array> + ? InfiniteData + : TData) +> { + return fetchQuery(client, infiniteFetchOptions(options) as any) +} diff --git a/packages/react-query-pluggable/src/runtime/hydration.ts b/packages/react-query-pluggable/src/runtime/hydration.ts new file mode 100644 index 00000000000..27af3fd9f62 --- /dev/null +++ b/packages/react-query-pluggable/src/runtime/hydration.ts @@ -0,0 +1,420 @@ +import { noop } from '@tanstack/query-core/primitives' +import { prepareInfiniteFetch } from './infiniteQueryBehavior' +import { Mutation } from './mutation' +import { + getDefaultOptions, + getQueryCache, + mutationCacheKey, +} from './queryClient' +import { serialScope } from './serialScope' +import type { DefaultError, DehydratedState } from '@tanstack/query-core' +import type * as Core from '@tanstack/query-core' +import type { Query } from './query' +import type { QueryClient } from './queryClient' +import type { MutationOptions, QueryOptions } from './types' + +type DehydratedMutation = DehydratedState['mutations'][number] + +type DehydratedQuery = DehydratedState['queries'][number] + +type TransformerFn = NonNullable + +/** + * Options for `dehydrate`, controlling which queries/mutations are included in the resulting `DehydratedState` and + * how their data/errors are transformed before being serialized (e.g. for embedding in server-rendered markup). + */ +export interface DehydrateOptions extends Omit< + Core.DehydrateOptions, + 'shouldDehydrateMutation' | 'shouldDehydrateQuery' +> { + /** Predicate to decide whether a given `Mutation` should be dehydrated. Defaults to `defaultShouldDehydrateMutation`. */ + shouldDehydrateMutation?: (mutation: Mutation) => boolean + /** Predicate to decide whether a given `Query` should be dehydrated. Defaults to `defaultShouldDehydrateQuery`. */ + shouldDehydrateQuery?: (query: Query) => boolean +} + +/** + * Options for `hydrate`, controlling the default options applied to queries/mutations restored from a + * `DehydratedState`, and how to reverse any transformation applied by `DehydrateOptions.serializeData`. + */ +export interface HydrateOptions { + /** Options applied to the queries and mutations restored from the dehydrated state. */ + defaultOptions?: { + /** Transforms a query's `data` after it is read from the dehydrated state, reversing `serializeData`. */ + deserializeData?: TransformerFn + /** Default options merged into every query restored from the dehydrated state. */ + queries?: QueryOptions + /** Default options merged into every mutation restored from the dehydrated state. */ + mutations?: MutationOptions + } +} + +/** + * Reads the value of a promise synchronously if it has already resolved, e.g. a thenable that + * resolves within its `then` call. + * @param promise - The promise to read. + * @returns An object with the resolved `data`, or `undefined` if the promise hasn't resolved + * synchronously (or resolved with `undefined`). + */ +function tryResolveSync(promise: PromiseLike) { + let data: unknown + + const thenResult = promise.then((result) => { + data = result + return result + }, noop) as Partial> | undefined + + // A synchronous thenable may return an object without a catch method. + thenResult?.catch?.(noop) + + if (data !== undefined) { + return { data } + } + + return undefined +} + +// FUNCTIONS + +/** + * Dehydrates a single `Mutation` into a serializable snapshot of its key, state, scope, and meta. + * @param mutation - The mutation to dehydrate. + * @returns The dehydrated mutation. + */ +function dehydrateMutation(mutation: Mutation): DehydratedMutation { + return { + mutationKey: mutation.options.mutationKey, + state: mutation.state, + ...(mutation.options.scope && { scope: { id: mutation.options.scope.id } }), + ...(mutation.meta && { meta: mutation.meta }), + } +} + +/** + * Prepares the in-flight promise of a pending query for dehydration: applies `serializeData` to its + * result, and redacts its rejection error unless `shouldRedactErrors` returns `false` for it. + * @param query - The pending query whose promise is dehydrated. + * @param serializeData - Optional transform applied to the resolved data. + * @param shouldRedactErrors - Optional predicate; if it returns `false` for the rejection error, + * that + * error is kept as-is instead of being redacted. + * @returns The transformed promise, or `undefined` if the query has no in-flight promise. + */ +function dehydratePromise( + query: Query, + serializeData?: TransformerFn, + shouldRedactErrors?: (error: unknown) => boolean, +): Promise | undefined { + const promise = query.promise?.then(serializeData).catch((error) => { + if (shouldRedactErrors?.(error) === false) { + // Reject original error if it should not be redacted + return Promise.reject(error) + } + // If not in production, log original error before rejecting redacted error + if (process.env.NODE_ENV !== 'production') { + console.error( + `A query that was dehydrated as pending ended up rejecting. [${query.queryHash}]: ${error}; The error will be redacted in production builds`, + ) + } + return Promise.reject(new Error('redacted')) + }) + + // Avoid unhandled promise rejections + // We need the promise we dehydrate to reject to get the correct result into + // the query cache, but we also want to avoid unhandled promise rejections + // in whatever environment the prefetches are happening in. + promise?.catch(noop) + + return promise +} + +/** + * Dehydrates a single `Query` into a serializable `DehydratedQuery` snapshot. Note that most query config (e.g. + * `queryFn`, `staleTime`) is not dehydrated but instead meant to be configured again when consuming the + * de/rehydrated data, typically with `useQuery` on the client. If the query is still `pending`, its in-flight + * promise is dehydrated too so it can be resumed on the other side instead of re-fetched. + * @param query - The query to dehydrate. + * @param serializeData - Optional transform applied to `query.state.data` before it is included in the snapshot. + * @param shouldRedactErrors - Optional predicate; if it returns `false` for the promise's rejection error, that + * error is kept as-is instead of being redacted. + * @returns The dehydrated query. + */ +export function dehydrateQuery( + query: Query, + serializeData?: TransformerFn, + shouldRedactErrors?: (error: unknown) => boolean, +): DehydratedQuery { + return { + dehydratedAt: Date.now(), + state: { + ...query.state, + ...(query.state.data !== undefined && { + data: serializeData + ? serializeData(query.state.data) + : query.state.data, + }), + }, + queryKey: query.queryKey, + queryHash: query.queryHash, + ...(query.state.status === 'pending' && { + promise: dehydratePromise(query, serializeData, shouldRedactErrors), + }), + ...(query.meta && { meta: query.meta }), + ...(query.queryType && { queryType: query.queryType }), + } +} + +/** + * The default `shouldDehydrateMutation` predicate used by `dehydrate`. Only dehydrates mutations that are + * currently paused (e.g. paused by `networkMode` while offline). + * @param mutation - The mutation to check. + * @returns `true` if the mutation is paused. + */ +export function defaultShouldDehydrateMutation(mutation: Mutation) { + return mutation.state.isPaused +} + +/** + * The default `shouldDehydrateQuery` predicate used by `dehydrate`. Only dehydrates queries whose status is + * `'success'`. + * @param query - The query to check. + * @returns `true` if the query's status is `'success'`. + */ +export function defaultShouldDehydrateQuery(query: Query) { + return query.state.status === 'success' +} + +/** + * Dehydrates a `QueryClient`'s cache (queries and mutations) into a plain, serializable `DehydratedState`, + * typically to embed in server-rendered markup and later restore into a client-side `QueryClient` via `hydrate`. + * Which queries/mutations are included, and how their data/errors are transformed, is controlled by `options`, + * falling back to the client's `dehydrate` default options, and finally to `defaultShouldDehydrateQuery` / + * `defaultShouldDehydrateMutation`. + * @param client - The client whose cache is dehydrated. + * @param options - Controls which queries and mutations are included and how their data and errors + * are transformed. Each option falls back to the client's `defaultOptions.dehydrate`. + * @returns The dehydrated state, with the included `queries` and `mutations`. + * @example + * ```ts + * const queryClient = new QueryClient() + * + * await fetchQuery(queryClient, { + * queryKey: ['posts'], + * queryFn: getPosts, + * }) + * + * const dehydratedState = dehydrate(queryClient) + * ``` + */ +export function dehydrate( + client: QueryClient, + options: DehydrateOptions = {}, +): DehydratedState { + const filterMutation = + options.shouldDehydrateMutation ?? + getDefaultOptions(client).dehydrate?.shouldDehydrateMutation ?? + defaultShouldDehydrateMutation + + const mutations = + client[mutationCacheKey] + ?.getAll() + .flatMap((mutation) => + filterMutation(mutation) ? [dehydrateMutation(mutation)] : [], + ) ?? [] + + const filterQuery = + options.shouldDehydrateQuery ?? + getDefaultOptions(client).dehydrate?.shouldDehydrateQuery ?? + defaultShouldDehydrateQuery + + const shouldRedactErrors = + options.shouldRedactErrors ?? + getDefaultOptions(client).dehydrate?.shouldRedactErrors + + const serializeData = + options.serializeData ?? getDefaultOptions(client).dehydrate?.serializeData + + const queries = getQueryCache(client) + .getAll() + .flatMap((query) => + filterQuery(query) + ? [dehydrateQuery(query, serializeData, shouldRedactErrors)] + : [], + ) + + return { mutations, queries } +} + +/** + * Restores a `DehydratedState` (as produced by `dehydrate`) into a `QueryClient`'s cache, typically to seed the + * client with data already fetched on the server. `mutations` and `queries` are each optional on `dehydratedState`. + * Queries not yet in the cache are built from the dehydrated snapshot; queries that already exist are only updated + * when the dehydrated data is newer than what's already cached. Newly built queries have their `fetchStatus` reset + * to `'idle'` so they don't hydrate stuck in a fetching state. If a dehydrated query still had an in-flight + * promise, it is resumed via `query.fetch()` (reusing that promise as `initialPromise`) rather than re-invoking + * `queryFn`. + * @param client - The client whose cache is restored into. + * @param dehydratedState - The dehydrated state, e.g. produced by `dehydrate` on the server. + * @param options - `defaultOptions` merged into every restored query and mutation (on top of the + * client's `defaultOptions.hydrate`), and `deserializeData` to reverse `serializeData`. + * @example + * ```ts + * // dehydratedState was produced by `dehydrate` on the server + * // and sent to the client, e.g. embedded in server-rendered markup. + * const queryClient = new QueryClient() + * + * hydrate(queryClient, dehydratedState) + * ``` + */ +export function hydrate( + client: QueryClient, + dehydratedState: Partial, + options?: HydrateOptions, +): void { + dehydratedState.mutations?.forEach(({ state, scope, ...mutationOptions }) => { + Mutation.build( + client, + { + ...getDefaultOptions(client).hydrate?.mutations, + ...options?.defaultOptions?.mutations, + ...mutationOptions, + ...(scope && { scope: serialScope(scope.id) }), + }, + state, + ) + }) + + if (dehydratedState.queries) + hydrateQueries(client, dehydratedState.queries, options) +} + +/** + * Restores just the queries accepted by a React hydration boundary. + * @internal + * @param client - The client receiving the entries. + * @param queries - The serialized query entries. + * @param options - Query restoration settings. + */ +export function hydrateQueries( + client: QueryClient, + queries: Array, + options?: HydrateOptions, +): void { + const queryCache = getQueryCache(client) + const deserializeData = + options?.defaultOptions?.deserializeData ?? + getDefaultOptions(client).hydrate?.deserializeData + + queries.forEach( + ({ + queryKey, + state, + queryHash, + meta, + promise, + dehydratedAt, + queryType, + }) => { + const syncData = promise ? tryResolveSync(promise) : undefined + const rawData = state.data === undefined ? syncData?.data : state.data + const data = + rawData === undefined + ? rawData + : deserializeData + ? deserializeData(rawData) + : rawData + + let query = queryCache.get(queryHash) + const existingQueryIsPending = query?.state.status === 'pending' + const existingQueryIsFetching = query?.state.fetchStatus === 'fetching' + + // Do not hydrate if an existing query exists with newer data + if (query) { + const hasNewerSyncData = + syncData && dehydratedAt > query.state.dataUpdatedAt + if ( + state.dataUpdatedAt > query.state.dataUpdatedAt || + hasNewerSyncData + ) { + // Omit fetchStatus from dehydrated state so that query stays in its current fetchStatus + const { fetchStatus: _ignored, ...serializedState } = state + query.setState({ + ...serializedState, + data, + // If the query was pending at the moment of dehydration, but resolved to have data + // before hydration, we can assume the query should be hydrated as successful. + // + // Since you can opt into dehydrating failed queries, and those can have data from + // previous successful fetches, we make sure we only do this for pending queries. + ...(state.status === 'pending' && + data !== undefined && { + status: 'success' as const, + dataUpdatedAt: dehydratedAt, + // Preserve existing fetchStatus if the existing query is actively fetching. + ...(!existingQueryIsFetching && { + fetchStatus: 'idle' as const, + }), + }), + }) + } + } else { + // Restore query + query = queryCache.build( + client, + { + ...getDefaultOptions(client).hydrate?.queries, + ...options?.defaultOptions?.queries, + queryKey, + queryHash, + meta, + ...(queryType === 'infinite' && { + _type: queryType, + _prepareInfiniteFetch: prepareInfiniteFetch, + }), + }, + // Reset fetch status to idle to avoid + // query being stuck in fetching state upon hydration + { + ...state, + data, + fetchStatus: 'idle', + // Like above, if the query was pending at the moment of dehydration but has data, + // we can assume it should be hydrated as successful. + status: + state.status === 'pending' && data !== undefined + ? 'success' + : state.status, + ...(state.status === 'pending' && + data !== undefined && { + dataUpdatedAt: dehydratedAt, + }), + }, + ) + } + + if ( + promise && + // If the data was synchronously available, there is no need to set up + // a retryer and thus no reason to call fetch + !syncData && + !existingQueryIsPending && + !existingQueryIsFetching && + // Only hydrate if dehydration is newer than any existing data, + // this is always true for new queries + dehydratedAt > query.state.dataUpdatedAt + ) { + // This doesn't actually fetch - it just creates a retryer + // which will re-use the passed `initialPromise` + query + .fetch(undefined, { + // RSC transformed promises are not thenable + initialPromise: Promise.resolve(promise).then(deserializeData), + }) + // Avoid unhandled promise rejections + .catch(noop) + } + }, + ) +} + +export type { DehydratedState } from '@tanstack/query-core' diff --git a/packages/react-query-pluggable/src/runtime/identity.ts b/packages/react-query-pluggable/src/runtime/identity.ts new file mode 100644 index 00000000000..d6857688755 --- /dev/null +++ b/packages/react-query-pluggable/src/runtime/identity.ts @@ -0,0 +1,9 @@ +/** + * Returns its argument by reference. Option helpers specialize the signature with + * their own overloads and add their key tags at compile time. + * @param value - The original value. + * @returns The original value. + */ +export function identity(value: T): T { + return value +} diff --git a/packages/react-query-pluggable/src/runtime/infiniteQueryBehavior.ts b/packages/react-query-pluggable/src/runtime/infiniteQueryBehavior.ts new file mode 100644 index 00000000000..8a5d9a127ca --- /dev/null +++ b/packages/react-query-pluggable/src/runtime/infiniteQueryBehavior.ts @@ -0,0 +1,199 @@ +import { + addConsumeAwareSignal, + addToArray, + fetchSignal, +} from '@tanstack/query-core/primitives' +import { ensureQueryFn } from './utils' +import type { FetchSignalContext } from '@tanstack/query-core/primitives' +import type { FetchContext, Query } from './query' +import type { InfiniteData, InfiniteQueryPageParamsOptions } from './types' + +/** + * Installs the page fetcher for an infinite query. A retry continues from the + * failed page. A new fetch starts with the most recently cached pages. + * @param context - The fetch in progress, including its options and cached pages. + * @param query - The query supplied to a custom persister. + */ +export function prepareInfiniteFetch( + context: FetchContext>, + query: Query, +): void { + const options = context.options as InfiniteQueryPageParamsOptions & { + pages?: number + } + const direction = context.fetchOptions?.meta?.fetchMore?.direction + const oldPages = context.state.data?.pages || [] + const oldPageParams = context.state.data?.pageParams || [] + let result: InfiniteData = { pages: [], pageParams: [] } + let currentPage = 0 + + const fetchFn = async () => { + let cancelled = false + const signalContext: FetchSignalContext = context + const queryFn = ensureQueryFn(context.options, context.fetchOptions) + + // Create function to fetch a page + const fetchPage = async ( + data: InfiniteData, + param: unknown, + previous?: boolean, + ): Promise> => { + if (cancelled) { + return Promise.reject(context.signal.reason) + } + + if (param == null && data.pages.length) { + return Promise.resolve(data) + } + + const queryFnContext = addConsumeAwareSignal( + { + client: context.client, + queryKey: context.queryKey, + pageParam: param, + meta: context.options.meta, + }, + () => context.signal, + () => (cancelled = true), + signalContext[fetchSignal], + ) + + const page = await queryFn(queryFnContext) + + const { maxPages } = context.options + return { + pages: addToArray(data.pages, page, maxPages, previous), + pageParams: addToArray(data.pageParams, param, maxPages, previous), + } + } + + // fetch next / previous page? + if (direction && oldPages.length) { + const previous = direction === 'backward' + const pageParamFn = previous ? getPreviousPageParam : getNextPageParam + const oldData = { + pages: oldPages, + pageParams: oldPageParams, + } + const param = pageParamFn(options, oldData) + + result = await fetchPage(oldData, param, previous) + } else { + const remainingPages = options.pages ?? oldPages.length + + // Fetch all pages + do { + const param = + currentPage === 0 + ? oldPageParams[0] === undefined + ? options.initialPageParam + : oldPageParams[0] + : getNextPageParam(options, result) + if (currentPage > 0 && param == null) { + break + } + result = await fetchPage(result, param) + currentPage++ + } while (currentPage < remainingPages) + } + + return result + } + if (context.options.persister) { + context.fetchFn = () => { + return context.options.persister?.( + fetchFn as any, + { + client: context.client, + queryKey: context.queryKey, + meta: context.options.meta, + signal: context.signal, + }, + query, + ) + } + } else { + context.fetchFn = fetchFn + } +} + +/** + * Computes the page param of the page after the last one, with the `getNextPageParam` option. + * @param options - The infinite query options. + * @param data - The current pages and page params. + * @returns The next page param, or `undefined` if there are no pages yet. + */ +function getNextPageParam( + options: InfiniteQueryPageParamsOptions, + { pages, pageParams }: InfiniteData, +): unknown | undefined { + return pages.length > 0 + ? options.getNextPageParam( + pages.at(-1), + pages, + pageParams.at(-1), + pageParams, + ) + : undefined +} + +/** + * Computes the page param of the page before the first one, with the `getPreviousPageParam` + * option. + * @param options - The infinite query options. + * @param data - The current pages and page params. + * @returns The previous page param, or `undefined` if there are no pages yet or no + * `getPreviousPageParam` option. + */ +function getPreviousPageParam( + options: InfiniteQueryPageParamsOptions, + { pages, pageParams }: InfiniteData, +): unknown | undefined { + return pages.length > 0 + ? options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams) + : undefined +} + +/** + * Checks if there is a next page. + * @param options - The infinite query options with `getNextPageParam`. + * @param data - The current pages and page params. + * @returns `true` if `getNextPageParam` returns a value other than `null` or `undefined`. + */ +export function hasNextPage( + options: InfiniteQueryPageParamsOptions, + data?: InfiniteData, +): boolean { + if (!data) return false + return getNextPageParam(options, data) != null +} + +/** + * Checks if there is a previous page. + * @param options - The infinite query options with `getPreviousPageParam`. + * @param data - The current pages and page params. + * @returns `true` if `getPreviousPageParam` is set and returns a value other than `null` or + * `undefined`. + */ +export function hasPreviousPage( + options: InfiniteQueryPageParamsOptions, + data?: InfiniteData, +): boolean { + if (!data || !options.getPreviousPageParam) return false + return getPreviousPageParam(options, data) != null +} + +/** + * Attaches paging to the options that create or restore an infinite query. + * @param options - Options accepted by an infinite query or observer. + * @returns Options that install the page fetcher on the cached query. + */ +export function infiniteFetchOptions( + options: TOptions, +) { + return { + ...options, + _type: 'infinite' as const, + _prepareInfiniteFetch: prepareInfiniteFetch, + } +} diff --git a/packages/react-query-pluggable/src/runtime/infiniteQueryObserver.ts b/packages/react-query-pluggable/src/runtime/infiniteQueryObserver.ts new file mode 100644 index 00000000000..04555d44a81 --- /dev/null +++ b/packages/react-query-pluggable/src/runtime/infiniteQueryObserver.ts @@ -0,0 +1,290 @@ +import { + hasNextPage, + hasPreviousPage, + infiniteFetchOptions, +} from './infiniteQueryBehavior' +import { QueryObserver } from './queryObserver' +import type { Subscribable } from '@tanstack/query-core/primitives' +import type { Query } from './query' +import type { QueryClient } from './queryClient' +import type { + QueryObserverResultContext, + QueryObserverResultReader, +} from './queryObserver' +import type { + DefaultError, + DefaultedInfiniteQueryObserverOptions, + FetchNextPageOptions, + FetchPreviousPageOptions, + InfiniteData, + InfiniteQueryObserverBaseResult, + InfiniteQueryObserverOptions, + InfiniteQueryObserverResult, + QueryKey, + QueryObserverResult, +} from './types' + +type InfiniteQueryObserverListener = ( + result: InfiniteQueryObserverResult, +) => void + +type ReplaceReturnType< + TFunction extends (...args: Array) => unknown, + TReturn, +> = (...args: Parameters) => TReturn + +type InfiniteObserverOptionsInput< + TQueryFnData, + TError, + TData, + TQueryKey extends QueryKey, + TPageParam, +> = + | InfiniteQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + > + | DefaultedInfiniteQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + > + +/** + * An `InfiniteQueryObserver` extends `QueryObserver` to observe and switch + * between infinite queries. It augments the base `QueryObserverResult` with + * infinite-query-specific fields and methods, such as `hasNextPage` and + * `fetchNextPage`, and is the primitive that framework adapters (e.g. + * `useInfiniteQuery`) build their hooks on top of. + * @example + * ```ts + * const observer = new InfiniteQueryObserver(queryClient, { + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextCursor, + * }) + * + * const unsubscribe = observer.subscribe((result) => console.log(result)) + * ``` + */ +export class InfiniteQueryObserver< + TQueryFnData = unknown, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> extends QueryObserver< + TQueryFnData, + TError, + TData, + InfiniteData, + TQueryKey +> { + // Type override + override subscribe!: Subscribable< + InfiniteQueryObserverListener + >['subscribe'] + + // Type override + override getCurrentResult!: ReplaceReturnType< + QueryObserver< + TQueryFnData, + TError, + TData, + InfiniteData, + TQueryKey + >['getCurrentResult'], + InfiniteQueryObserverResult + > + + // Type override + protected override fetch!: ReplaceReturnType< + QueryObserver< + TQueryFnData, + TError, + TData, + InfiniteData, + TQueryKey + >['fetch'], + Promise> + > + + constructor( + client: QueryClient, + options: InfiniteObserverOptionsInput< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + ) { + super(client, options) + } + + protected override bindMethods(): void { + super.bindMethods() + this.fetchNextPage = this.fetchNextPage.bind(this) + this.fetchPreviousPage = this.fetchPreviousPage.bind(this) + } + + /** + * Updates the observer's options. Behaves the same as + * `QueryObserver.setOptions`, additionally marking the options as + * belonging to an infinite query before delegating to the base + * implementation. + * @param options - The new infinite query observer options. + */ + override setOptions( + options: InfiniteObserverOptionsInput< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + ): void { + super.setOptions(infiniteFetchOptions(options)) + } + + /** + * Creates a cached snapshot reader for an infinite query. + * @param options - The defaulted options used to read and commit the query result. + * @returns A reader that keeps its result and computation state until commit. + */ + override createResultReader( + options: DefaultedInfiniteQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + ): QueryObserverResultReader> { + return super.createResultReader( + infiniteFetchOptions(options), + ) as QueryObserverResultReader> + } + + /** + * Fetches the next page of the infinite query and returns a promise that + * resolves with the resulting `InfiniteQueryObserverResult`. The page + * param used for the fetch is determined by `getNextPageParam`, which + * receives the current pages/page params and whose result also determines + * `hasNextPage`. + * @param options - Set `cancelRefetch` to `false` to ignore the call while a fetch is running, + * and `throwOnError` to `true` to reject when the fetch fails. + * @returns A promise that resolves with the result after the next page is fetched. With + * `cancelRefetch: false`, a running fetch is reused instead, so the next page may not be fetched. + * @see {@link InfiniteQueryObserver#fetchPreviousPage} + * @example + * ```ts + * const { hasNextPage } = observer.getCurrentResult() + * + * if (hasNextPage) { + * await observer.fetchNextPage() + * } + * ``` + */ + fetchNextPage( + options?: FetchNextPageOptions, + ): Promise> { + return this.fetch({ + ...options, + meta: { + fetchMore: { direction: 'forward' }, + }, + }) + } + + /** + * Fetches the previous page of the infinite query and returns a promise + * that resolves with the resulting `InfiniteQueryObserverResult`. The page + * param used for the fetch is determined by `getPreviousPageParam`, which + * receives the current pages/page params and whose result also determines + * `hasPreviousPage`. + * @param options - Set `cancelRefetch` to `false` to ignore the call while a fetch is running, + * and `throwOnError` to `true` to reject when the fetch fails. + * @returns A promise that resolves with the result after the previous page is fetched. With + * `cancelRefetch: false`, a running fetch is reused instead, so the previous page may not be fetched. + * @see {@link InfiniteQueryObserver#fetchNextPage} + * @example + * ```ts + * const { hasPreviousPage } = observer.getCurrentResult() + * + * if (hasPreviousPage) { + * await observer.fetchPreviousPage() + * } + * ``` + */ + fetchPreviousPage( + options?: FetchPreviousPageOptions, + ): Promise> { + return this.fetch({ + ...options, + meta: { + fetchMore: { direction: 'backward' }, + }, + }) + } + + protected override createResult( + query: Query< + TQueryFnData, + TError, + InfiniteData, + TQueryKey + >, + options: InfiniteObserverOptionsInput< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + context?: QueryObserverResultContext< + TQueryFnData, + TError, + TData, + InfiniteData, + TQueryKey + >, + prevResult?: QueryObserverResult, + ): InfiniteQueryObserverResult { + const { state } = query + const parentResult = super.createResult(query, options, context, prevResult) + + const { isFetching, isRefetching, isError, isRefetchError } = parentResult + const fetchDirection = state.fetchMeta?.fetchMore?.direction + + const isFetchNextPageError = isError && fetchDirection === 'forward' + const isFetchingNextPage = isFetching && fetchDirection === 'forward' + + const isFetchPreviousPageError = isError && fetchDirection === 'backward' + const isFetchingPreviousPage = isFetching && fetchDirection === 'backward' + + const result: InfiniteQueryObserverBaseResult = { + ...parentResult, + fetchNextPage: this.fetchNextPage, + fetchPreviousPage: this.fetchPreviousPage, + hasNextPage: hasNextPage(options, state.data), + hasPreviousPage: hasPreviousPage(options, state.data), + isFetchNextPageError, + isFetchingNextPage, + isFetchPreviousPageError, + isFetchingPreviousPage, + isRefetchError: + isRefetchError && !isFetchNextPageError && !isFetchPreviousPageError, + isRefetching: + isRefetching && !isFetchingNextPage && !isFetchingPreviousPage, + } + + return result as InfiniteQueryObserverResult + } +} diff --git a/packages/react-query-pluggable/src/runtime/mutation.ts b/packages/react-query-pluggable/src/runtime/mutation.ts new file mode 100644 index 00000000000..92fe8a700eb --- /dev/null +++ b/packages/react-query-pluggable/src/runtime/mutation.ts @@ -0,0 +1,501 @@ +import { Removable, createRetryer } from '@tanstack/query-core/primitives' +import { getMutationCache } from './mutationCache' +import { notifyManager } from './notifyManager' +import { defaultMutationOptions } from './queryClient' +import type { MutationState } from '@tanstack/query-core' +import type { + MutationAction as Action, + Retryer, +} from '@tanstack/query-core/primitives' +import type { MutationCache } from './mutationCache' +import type { MutationObserver } from './mutationObserver' +import type { QueryClient } from './queryClient' +import type { + DefaultError, + MutationFunctionContext, + MutationMeta, + MutationOptions, +} from './types' + +interface MutationConfig { + client: QueryClient + mutationId: number + mutationCache: MutationCache + options: MutationOptions + state?: MutationState +} + +// CLASS + +/** + * Represents a single mutation attempt. A `Mutation` holds the mutation's + * options, state (data/error/status), and the `MutationObserver`s currently + * subscribed to it. + * + * Instances are created and managed internally by `MutationCache`; application + * code typically interacts with mutations indirectly through `QueryClient` or + * a framework hook like `useMutation`. Direct access to a `Mutation` instance + * is possible via `mutationCache.find()`/`getAll()` for inspecting cache state. + * @example + * ```ts + * const mutationCache = getMutationCache(queryClient) + * + * const mutation = mutationCache.find({ mutationKey: ['addPost'] }) + * ``` + */ +export class Mutation< + TData = unknown, + TError = DefaultError, + TVariables = unknown, + TOnMutateResult = unknown, +> extends Removable { + state: MutationState + options!: MutationOptions + readonly mutationId: number + + #client: QueryClient + #observers: Array< + MutationObserver + > + #mutationCache: MutationCache + #retryer?: Retryer + + /** + * Creates a mutation with the client's defaults and adds it to the cache. + * @param client - Supplies defaults and the mutation cache. + * @param options - The options for the new mutation. + * @param state - The initial state, for example when hydrating a paused mutation. + * @returns The registered mutation. + */ + static build( + client: QueryClient, + options: MutationOptions, + state?: MutationState, + ): Mutation { + const cache = getMutationCache(client) + return cache.register( + (mutationId) => + new Mutation({ + client, + mutationCache: cache, + mutationId, + options: defaultMutationOptions(client, options), + state, + }), + ) + } + + constructor( + config: MutationConfig, + ) { + super() + + this.#client = config.client + this.mutationId = config.mutationId + this.#mutationCache = config.mutationCache + this.#observers = [] + this.state = config.state || getDefaultState() + + this.options = config.options + this.updateGcTime(config.options.gcTime) + this.scheduleGc() + } + + /** + * Replaces the mutation's options and applies their `gcTime`. + * @internal + * @param options - The new mutation options. + */ + setOptions( + options: MutationOptions, + ): void { + // An observer may change options while its previous mutation is still queued. + const scope = this.options.scope + this.options = options.scope === scope ? options : { ...options, scope } + this.updateGcTime(options.gcTime) + } + + /** + * The `meta` object passed in the mutation's options, if any. + * @returns The mutation's `meta`, or `undefined` if none was set. + */ + get meta(): MutationMeta | undefined { + return this.options.meta + } + + /** + * Subscribes an observer to the mutation and stops its garbage collection. + * @internal + * @param observer - The observer to add. Adding an observer that is already subscribed does + * nothing. + */ + addObserver(observer: MutationObserver): void { + if (!this.#observers.includes(observer)) { + this.#observers.push(observer) + + // Stop the mutation from being garbage collected + this.clearGcTimeout() + + this.#mutationCache.notify({ + type: 'observerAdded', + mutation: this, + observer, + }) + } + } + + /** + * Unsubscribes an observer from the mutation. + * @internal + * @param observer - The observer to remove. Schedules garbage collection if the mutation + * is still in the cache. + */ + removeObserver(observer: MutationObserver): void { + this.#observers = this.#observers.filter((x) => x !== observer) + + if (this.#mutationCache.has(this)) { + this.scheduleGc() + } + + this.#mutationCache.notify({ + type: 'observerRemoved', + mutation: this, + observer, + }) + } + + protected override optionalRemove() { + if (!this.#observers.length) { + if (this.state.status === 'pending') { + this.scheduleGc() + } else { + this.#mutationCache.remove(this) + } + } + } + + /** + * Resumes a mutation that is currently paused or was restored from a + * dehydrated, still-`pending` state. + * + * - If this mutation has an active retryer (it paused mid-attempt, e.g. due + * to the network mode or scope-based queuing), its retryer is resumed. + * - Otherwise, if the mutation's status is still `pending` (e.g. it was + * dehydrated while an attempt was in flight and never got a retryer in + * this instance), `execute` is called again with the last known variables. + * - Otherwise the mutation has already settled and this resolves immediately + * without running anything again. + * @returns A promise that settles with the resumed mutation: it rejects if the mutation fails. + * It resolves immediately if the mutation has already settled. + * @see {@link Mutation#execute} + * @example + * ```ts + * // typically driven by reconnect handling, e.g. queryClient.resumePausedMutations() + * const mutation = mutationCache.find({ mutationKey: ['addPost'] }) + * await mutation?.continue() + * ``` + */ + continue(): Promise { + return ( + this.#retryer?.continue() ?? + // continuing a mutation assumes that variables are set, mutation must have been dehydrated before. + // a settled mutation has no retryer to continue and must not run again + (this.state.status === 'pending' + ? this.execute(this.state.variables!) + : Promise.resolve()) + ) + } + + /** + * Runs the mutation function for the given variables through a retryer, and + * drives the mutation's state and lifecycle callbacks through to settlement. + * + * If this mutation's state is already `pending` when `execute` is called + * (i.e. it was restored, still in-flight, from a dehydrated state), the + * `onMutate` step is skipped and a `continue` action is dispatched to + * unpause it; otherwise a `pending` action is dispatched first, then the + * mutation cache's `onMutate` and the mutation's own `onMutate` option are + * awaited in that order, and the resulting context is stored. + * + * The mutation function is then run (subject to `retry`/`retryDelay`/ + * `networkMode`, and to the mutation cache's scope-based serialization). + * On success, the cache's `onSuccess`/`onSettled` callbacks run before the + * mutation's own `onSuccess`/`onSettled` options, a `success` action is + * dispatched, and the resolved data is returned. On failure, the same + * cache-then-option ordering is used for `onError`/`onSettled`, but each of + * those four callbacks is individually caught so that a throwing callback + * cannot mask the original error; an `error` action is then dispatched and + * the original error is re-thrown. + * @param variables - The variables passed to the `mutationFn`. + * @returns A promise that resolves with the mutation's data, or rejects with its error. + * @see {@link Mutation#continue} + * @example + * ```ts + * // Called internally by `MutationObserver.mutate` and `Mutation.continue` — + * // applications normally trigger mutations through those, not this method. + * const data = await mutation.execute(variables) + * ``` + */ + async execute(variables: TVariables): Promise { + const onContinue = () => { + this.#dispatch({ type: 'continue' }) + } + + const mutationFnContext = { + client: this.#client, + meta: this.options.meta, + mutationKey: this.options.mutationKey, + } satisfies MutationFunctionContext + + const retryer = (this.#retryer = createRetryer({ + fn: () => { + if (!this.options.mutationFn) { + return Promise.reject(new Error('No mutationFn found')) + } + + return this.options.mutationFn(variables, mutationFnContext) + }, + onFail: (failureCount, error) => { + this.#dispatch({ type: 'failed', failureCount, error }) + }, + onPause: () => { + this.#dispatch({ type: 'pause' }) + }, + onContinue, + retry: this.options.retry ?? 0, + retryDelay: this.options.retryDelay, + networkMode: this.options.networkMode, + canRun: () => this.#mutationCache.canRun(this), + })) + + const restored = this.state.status === 'pending' + const isPaused = !retryer.canStart() + + try { + if (restored) { + // Dispatch continue action to unpause restored mutation + onContinue() + } else { + this.#dispatch({ type: 'pending', variables, isPaused }) + // Notify cache callback + if (this.#mutationCache.config.onMutate) { + await this.#mutationCache.config.onMutate( + variables, + this as Mutation, + mutationFnContext, + ) + } + const context = await this.options.onMutate?.( + variables, + mutationFnContext, + ) + if (context !== this.state.context) { + this.#dispatch({ + type: 'pending', + context, + variables, + isPaused, + }) + } + } + // Unpause a mutation that became able to start while onMutate was running + if (this.state.isPaused && retryer.canStart()) { + onContinue() + } + const data = await retryer.start() + + // Notify cache callback + await this.#mutationCache.config.onSuccess?.( + data, + variables, + this.state.context, + this as Mutation, + mutationFnContext, + ) + + await this.options.onSuccess?.( + data, + variables, + this.state.context!, + mutationFnContext, + ) + + // Notify cache callback + await this.#mutationCache.config.onSettled?.( + data, + null, + this.state.variables, + this.state.context, + this as Mutation, + mutationFnContext, + ) + + await this.options.onSettled?.( + data, + null, + variables, + this.state.context, + mutationFnContext, + ) + + this.#dispatch({ type: 'success', data }) + return data + } catch (error) { + try { + // Notify cache callback + await this.#mutationCache.config.onError?.( + error as any, + variables, + this.state.context, + this as Mutation, + mutationFnContext, + ) + } catch (e) { + void Promise.reject(e) + } + + try { + await this.options.onError?.( + error as TError, + variables, + this.state.context, + mutationFnContext, + ) + } catch (e) { + void Promise.reject(e) + } + + try { + // Notify cache callback + await this.#mutationCache.config.onSettled?.( + undefined, + error as any, + this.state.variables, + this.state.context, + this as Mutation, + mutationFnContext, + ) + } catch (e) { + void Promise.reject(e) + } + + try { + await this.options.onSettled?.( + undefined, + error as TError, + variables, + this.state.context, + mutationFnContext, + ) + } catch (e) { + void Promise.reject(e) + } + + this.#dispatch({ type: 'error', error: error as TError }) + throw error + } finally { + // The settled retryer's promise would otherwise pin this mutation's + // result, variables and context for as long as the cache keeps it + if (this.#retryer === retryer) { + this.#retryer = undefined + } + this.#mutationCache.runNext(this) + } + } + + #dispatch(action: Action): void { + const reducer = ( + state: MutationState, + ): MutationState => { + switch (action.type) { + case 'failed': + return { + ...state, + failureCount: action.failureCount, + failureReason: action.error, + } + case 'pause': + return { + ...state, + isPaused: true, + } + case 'continue': + return { + ...state, + isPaused: false, + } + case 'pending': + return { + ...state, + context: action.context, + data: undefined, + failureCount: 0, + failureReason: null, + error: null, + isPaused: action.isPaused, + status: 'pending', + variables: action.variables, + submittedAt: Date.now(), + } + case 'success': + return { + ...state, + data: action.data, + failureCount: 0, + failureReason: null, + error: null, + status: 'success', + isPaused: false, + } + case 'error': + return { + ...state, + data: undefined, + error: action.error, + failureCount: state.failureCount + 1, + failureReason: action.error, + isPaused: false, + status: 'error', + } + } + } + this.state = reducer(this.state) + + notifyManager.batch(() => { + this.#observers.forEach((observer) => { + observer.onMutationUpdate(action) + }) + this.#mutationCache.notify({ + mutation: this, + type: 'updated', + action, + }) + }) + } +} + +/** + * Returns the initial state of a mutation: `'idle'`, with no data, error, or variables. + * @returns The initial mutation state. + */ +export function getDefaultState< + TData, + TError, + TVariables, + TOnMutateResult, +>(): MutationState { + return { + context: undefined, + data: undefined, + error: null, + failureCount: 0, + failureReason: null, + isPaused: false, + status: 'idle', + variables: undefined, + submittedAt: 0, + } +} + +export type { MutationState } from '@tanstack/query-core' +export type { MutationAction as Action } from '@tanstack/query-core/primitives' diff --git a/packages/react-query-pluggable/src/runtime/mutationCache.ts b/packages/react-query-pluggable/src/runtime/mutationCache.ts new file mode 100644 index 00000000000..110acf28dc1 --- /dev/null +++ b/packages/react-query-pluggable/src/runtime/mutationCache.ts @@ -0,0 +1,345 @@ +import { Subscribable, noop } from '@tanstack/query-core/primitives' +import { notifyManager } from './notifyManager' +import { mutationCacheKey } from './queryClient' +import { matchMutation } from './utils' +import type { + CacheKeyConfig, + MutationKey, + NotifyEvent, +} from '@tanstack/query-core' +import type { MutationAction } from '@tanstack/query-core/primitives' +import type { Mutation } from './mutation' +import type { MutationObserver } from './mutationObserver' +import type { QueryClient } from './queryClient' +import type { DefaultError, MutationFunctionContext } from './types' +import type { MutationFilters } from './utils' + +/** + * Global callbacks that fire for every mutation handled by a `MutationCache`, regardless of which + * component or observer triggered it. They differ from the `defaultOptions` provided to a + * `QueryClient` in two ways: `defaultOptions` can be overridden by each mutation, while these + * callbacks are always called, and `onMutate` here does not allow returning a result. + * + * If a callback returns a promise, it will be awaited before the mutation continues. + */ +export interface MutationCacheConfig { + /** + * Configures mutation key comparison and hashing globally. + * `equalityFn` compares individual values during partial matching and defaults to strict equality. + * `hashFn` hashes mutation keys for exact matching and mutation defaults. + */ + mutationKey?: CacheKeyConfig + /** Called when any mutation in the cache encounters an error. */ + onError?: ( + error: DefaultError, + variables: unknown, + onMutateResult: unknown, + mutation: Mutation, + context: MutationFunctionContext, + ) => Promise | unknown + /** Called when any mutation in the cache is successful. */ + onSuccess?: ( + data: unknown, + variables: unknown, + onMutateResult: unknown, + mutation: Mutation, + context: MutationFunctionContext, + ) => Promise | unknown + /** Called before any mutation in the cache executes. */ + onMutate?: ( + variables: unknown, + mutation: Mutation, + context: MutationFunctionContext, + ) => Promise | unknown + /** Called when any mutation in the cache is settled, either successfully or with an error. */ + onSettled?: ( + data: unknown | undefined, + error: DefaultError | null, + variables: unknown, + onMutateResult: unknown, + mutation: Mutation, + context: MutationFunctionContext, + ) => Promise | unknown +} + +/** + * The event passed to a `MutationCache` subscriber. Fired whenever a mutation is added or removed + * from the cache, its state is updated, or one of its observers is added, removed, or has its + * options updated. + */ +export type MutationCacheNotifyEvent = + | NotifyEventMutationAdded + | NotifyEventMutationRemoved + | NotifyEventMutationObserverAdded + | NotifyEventMutationObserverRemoved + | NotifyEventMutationObserverOptionsUpdated + | NotifyEventMutationUpdated + +type MutationCacheListener = (event: MutationCacheNotifyEvent) => void + +interface NotifyEventMutationAdded extends NotifyEvent { + type: 'added' + mutation: Mutation +} + +interface NotifyEventMutationRemoved extends NotifyEvent { + type: 'removed' + mutation: Mutation +} + +interface NotifyEventMutationObserverAdded extends NotifyEvent { + type: 'observerAdded' + mutation: Mutation + observer: MutationObserver +} + +interface NotifyEventMutationObserverRemoved extends NotifyEvent { + type: 'observerRemoved' + mutation: Mutation + observer: MutationObserver +} + +interface NotifyEventMutationObserverOptionsUpdated extends NotifyEvent { + type: 'observerOptionsUpdated' + mutation?: Mutation + observer: MutationObserver +} + +interface NotifyEventMutationUpdated extends NotifyEvent { + type: 'updated' + mutation: Mutation + action: MutationAction +} + +/** + * Returns the client's configured mutation cache, creating a default cache on + * first use. Mutation hooks and hydration share this cache. + * @param client - The client whose mutations you want to access. + * @returns The same mutation cache on every call for this client. + * @example + * ```ts + * import { getMutationCache } from '@tanstack/react-query-pluggable' + * + * const pending = getMutationCache(queryClient).findAll({ status: 'pending' }) + * ``` + */ +export function getMutationCache(client: QueryClient): MutationCache { + return (client[mutationCacheKey] ??= new MutationCache()) +} + +/** + * Stores the mutations executed through a client. Use {@link getMutationCache} to + * access the cache that mutation hooks use. Subscribe to it to receive updates + * when a mutation is added, removed, or changes state. + * @example + * ```ts + * const unsubscribe = mutationCache.subscribe((event) => { + * console.log(event.type, event.mutation) + * }) + * ``` + */ +export class MutationCache extends Subscribable { + #mutations: Set> + #mutationId: number + + constructor(public config: MutationCacheConfig = {}) { + super() + this.#mutations = new Set() + this.#mutationId = 0 + } + + /** + * Assigns the next cache-local ID and registers the mutation. + * @internal + * @param create - Constructs the mutation with the assigned ID. + * @returns The mutation added to this cache. + */ + register>( + create: (id: number) => T, + ): T { + const mutation = create(++this.#mutationId) + this.add(mutation) + return mutation + } + + /** + * Adds a mutation to the cache. + * @internal + * @param mutation - The mutation to add. If it has a `scope`, it is queued in that scope. + */ + add(mutation: Mutation): void { + this.#mutations.add(mutation) + mutation.options.scope?.add(this, mutation) + this.notify({ type: 'added', mutation }) + } + + /** + * Removes a mutation from the cache and clears its garbage collection timer. + * @internal + * @param mutation - The mutation to remove, also from its scope's queue. + */ + remove(mutation: Mutation): void { + if (this.#mutations.delete(mutation)) { + mutation.destroy() + mutation.options.scope?.remove(this, mutation) + } + + // Currently we notify the removal even if the mutation was already removed. + // Consider making this an error or not notifying of the removal depending on the desired semantics. + this.notify({ type: 'removed', mutation }) + } + + /** + * Checks whether this cache still holds the given mutation. + * @internal + * @param mutation - The mutation to check. + * @returns Whether the mutation is in the cache. + */ + has(mutation: Mutation): boolean { + return this.#mutations.has(mutation) + } + + /** + * Checks whether a mutation can run now, given the other mutations in its `scope`. + * @internal + * @param mutation - The mutation to check. + * @returns `true` if the mutation has no `scope`, or no other mutation in its scope is pending + * ahead of it. + */ + canRun(mutation: Mutation): boolean { + return mutation.options.scope?.canRun(this, mutation) ?? true + } + + /** + * Continues the next paused mutation in the same `scope` after a mutation finishes. + * @internal + * @param mutation - The mutation that finished. + * @returns A promise that resolves once the next paused mutation in the same scope has continued, + * or immediately if there is none. + */ + runNext(mutation: Mutation): Promise { + return mutation.options.scope?.runNext(this, mutation) ?? Promise.resolve() + } + + /** + * Removes all mutations and clears their garbage collection timers. + * Mutations that are already running continue to execute. + * @example + * ```ts + * const mutationCache = getMutationCache(queryClient) + * + * mutationCache.clear() + * ``` + */ + clear(): void { + notifyManager.batch(() => { + const mutations = this.getAll() + this.#mutations.clear() + mutations.forEach((mutation) => { + mutation.options.scope?.remove(this, mutation) + mutation.destroy() + }) + mutations.forEach((mutation) => { + this.notify({ type: 'removed', mutation }) + }) + }) + } + + /** + * Returns all mutations within the cache. + * + * This is not typically needed for most applications, but can come in handy when needing more + * information about a mutation in rare scenarios. + * @returns Every mutation in the cache. + * @example + * ```ts + * const mutationCache = getMutationCache(queryClient) + * + * const mutations = mutationCache.getAll() + * ``` + */ + getAll(): Array { + return Array.from(this.#mutations) + } + + /** + * A slightly more advanced method that can be used to get an existing mutation instance from + * the cache. If the mutation does not exist, `undefined` is returned. + * + * This is not typically needed for most applications, but can come in handy when needing more + * information about a mutation in rare scenarios. + * @param filters - The filters to match. `exact` defaults to `true`. + * @returns The first matching mutation, or `undefined`. + * @see {@link MutationCache#findAll} + * @example + * ```ts + * const mutationCache = getMutationCache(queryClient) + * + * const mutation = mutationCache.find({ mutationKey: ['addPost'] }) + * ``` + */ + find< + TData = unknown, + TError = DefaultError, + TVariables = any, + TOnMutateResult = unknown, + >( + filters: MutationFilters, + ): Mutation | undefined { + const defaultedFilters = { exact: true, ...filters } + + return this.getAll().find((mutation) => + matchMutation(defaultedFilters, mutation, this.config.mutationKey), + ) as Mutation | undefined + } + + /** + * An even more advanced method that can be used to get existing mutation instances from the + * cache that match the given filters. If no mutations match, an empty array is returned. + * + * This is not typically needed for most applications, but can come in handy when needing more + * information about mutations in rare scenarios. + * @param filters - The filters to match. Without filters, every mutation is returned. + * @returns The matching mutations. + * @see {@link MutationCache#find} + * @example + * ```ts + * const mutationCache = getMutationCache(queryClient) + * + * const mutations = mutationCache.findAll({ mutationKey: ['addPost'] }) + * ``` + */ + findAll(filters: MutationFilters = {}): Array { + return this.getAll().filter((mutation) => + matchMutation(filters, mutation, this.config.mutationKey), + ) + } + + /** + * Notifies every cache listener of an event, in one batch. + * @internal + * @param event - The event passed to every listener. + */ + notify(event: MutationCacheNotifyEvent) { + notifyManager.batch(() => { + this.listeners.forEach((listener) => { + listener(event) + }) + }) + } + + /** + * Continues every paused mutation, e.g. when the app comes back online. + * @internal + * @returns A promise that resolves once every paused mutation has continued and settled. + */ + resumePausedMutations(): Promise { + const pausedMutations = this.getAll().filter((x) => x.state.isPaused) + + return notifyManager.batch(() => + Promise.all( + pausedMutations.map((mutation) => mutation.continue().catch(noop)), + ), + ) + } +} diff --git a/packages/react-query-pluggable/src/runtime/mutationObserver.ts b/packages/react-query-pluggable/src/runtime/mutationObserver.ts new file mode 100644 index 00000000000..5e4b880940d --- /dev/null +++ b/packages/react-query-pluggable/src/runtime/mutationObserver.ts @@ -0,0 +1,330 @@ +import { + Subscribable, + hashKeyByOptions, + shallowEqualObjects, +} from '@tanstack/query-core/primitives' +import { Mutation, getDefaultState } from './mutation' +import { getMutationCache } from './mutationCache' +import { notifyManager } from './notifyManager' +import { defaultMutationOptions } from './queryClient' +import type { Action } from './mutation' +import type { QueryClient } from './queryClient' +import type { + DefaultError, + MutateOptions, + MutationFunctionContext, + MutationObserverOptions, + MutationObserverResult, +} from './types' + +type MutationObserverListener = ( + result: MutationObserverResult, +) => void + +// CLASS + +/** + * Observes a single mutation and derives a `MutationObserverResult` from it. + * A framework hook like `useMutation` creates one `MutationObserver` per hook + * call, keeps it stable across re-renders, calls `setOptions` when the options + * passed to the hook change, subscribes to it to re-render on updates, and + * reads `getCurrentResult()` for the value to return. Calling `mutate()` + * builds a new underlying `Mutation` in the `MutationCache` and executes it. + * @example + * ```ts + * const observer = new MutationObserver(queryClient, { + * mutationFn: (variables: { title: string }) => addPost(variables), + * }) + * ``` + */ +export class MutationObserver< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> extends Subscribable< + MutationObserverListener +> { + options!: MutationObserverOptions + + #client: QueryClient + #currentResult: MutationObserverResult< + TData, + TError, + TVariables, + TOnMutateResult + > = undefined! + #currentMutation?: Mutation + #mutateOptions?: MutateOptions + + constructor( + client: QueryClient, + options: MutationObserverOptions< + TData, + TError, + TVariables, + TOnMutateResult + >, + ) { + super() + + this.#client = client + this.setOptions(options) + this.bindMethods() + this.#updateResult() + } + + /** + * Binds the methods of the result (`mutate` and `reset`) to the observer, so they keep working when + * destructured from it. + */ + protected bindMethods(): void { + this.mutate = this.mutate.bind(this) + this.reset = this.reset.bind(this) + } + + /** + * Updates the observer's options. + * + * If the new `mutationKey` differs from the previous one (and both were + * defined), the observer is reset, detaching it from the mutation it was + * observing. Otherwise, if the currently observed mutation is still + * `pending`, its options are updated in place as well. + * @param options - The new mutation observer options. They are defaulted with {@link + * defaultMutationOptions} before being applied. + * @example + * ```ts + * observer.setOptions({ + * mutationFn: (variables: { title: string }) => addPost(variables), + * onSuccess: (data) => console.log(data), + * }) + * ``` + */ + setOptions( + options: MutationObserverOptions< + TData, + TError, + TVariables, + TOnMutateResult + >, + ) { + const prevOptions = this.options as + | MutationObserverOptions + | undefined + this.options = defaultMutationOptions(this.#client, options) + const mutationCache = getMutationCache(this.#client) + if (!shallowEqualObjects(this.options, prevOptions)) { + mutationCache.notify({ + type: 'observerOptionsUpdated', + mutation: this.#currentMutation, + observer: this, + }) + } + + if ( + prevOptions?.mutationKey && + this.options.mutationKey && + hashKeyByOptions( + prevOptions.mutationKey, + mutationCache.config.mutationKey, + ) !== + hashKeyByOptions( + this.options.mutationKey, + mutationCache.config.mutationKey, + ) + ) { + this.reset() + } else if (this.#currentMutation?.state.status === 'pending') { + this.#currentMutation.setOptions(this.options) + } + } + + protected override onSubscribe(): void { + if (this.listeners.size === 1 && this.#currentMutation) { + this.#currentMutation.addObserver(this) + + this.#updateResult() + } + } + + protected override onUnsubscribe(): void { + if (!this.hasListeners()) { + this.#currentMutation?.removeObserver(this) + } + } + + /** + * Updates the observer's result when the observed mutation changes, and notifies its listeners. + * @internal + * @param action - The action that updated the observed mutation, passed on to the observer's + * callbacks. + */ + onMutationUpdate( + action: Action, + ): void { + this.#updateResult() + + this.#notify(action) + } + + /** + * Returns the observer's current result, derived from the observed + * mutation's state (or the default, `idle` state if no mutation has been + * built yet, e.g. before the first `mutate()` call or after `reset()`). + * @returns The observer's latest result. + */ + getCurrentResult(): MutationObserverResult< + TData, + TError, + TVariables, + TOnMutateResult + > { + return this.#currentResult + } + + /** + * Detaches the observer from the mutation it is currently observing (if + * any) and resets the observed result back to its default, `idle` state. + * + * This does not cancel an in-flight mutation; the mutation itself keeps + * running to completion and its own callbacks still fire, but this + * observer stops reflecting its state and a subsequent `mutate()` call + * will build a brand new mutation. + * @see {@link MutationObserver#mutate} + * @example + * ```ts + * observer.reset() + * ``` + */ + reset(): void { + // reset needs to remove the observer from the mutation because there is no way to "get it back" + // another mutate call will yield a new mutation! + this.#currentMutation?.removeObserver(this) + this.#currentMutation = undefined + this.#updateResult() + this.#notify() + } + + /** + * Builds a new `Mutation` in the `MutationCache` using the observer's + * current options, detaches this observer from any previously observed + * mutation, attaches it to the new one, and executes it with the given + * variables. + * + * The optional per-call `options` (`onSuccess`/`onError`/`onSettled`) are + * invoked once the mutation settles, in addition to any callbacks defined + * on the observer's own options. + * @param variables - The variables passed to the `mutationFn`. + * @param options - Per-call `onSuccess`, `onError`, and `onSettled` callbacks. + * @returns A promise that resolves with the mutation's data, or rejects with its error. + * @example + * ```ts + * await observer.mutate( + * { title: 'New post' }, + * { onSuccess: (data) => console.log(data) }, + * ) + * ``` + */ + mutate( + variables: TVariables, + options?: MutateOptions, + ): Promise { + this.#mutateOptions = options + + this.#currentMutation?.removeObserver(this) + + this.#currentMutation = Mutation.build(this.#client, this.options) + + this.#currentMutation.addObserver(this) + + return this.#currentMutation.execute(variables) + } + + #updateResult(): void { + const state = + this.#currentMutation?.state ?? + getDefaultState() + + this.#currentResult = { + ...state, + isPending: state.status === 'pending', + isSuccess: state.status === 'success', + isError: state.status === 'error', + isIdle: state.status === 'idle', + mutate: this.mutate, + reset: this.reset, + } as MutationObserverResult + } + + #notify(action?: Action): void { + notifyManager.batch(() => { + // First trigger the mutate callbacks + // Snapshot mutateOptions before dispatching — a callback (e.g. onSuccess) + // may call mutate() again, which overwrites this.#mutateOptions in place. + // Without the snapshot, onSettled would fire with the *next* mutation's + // options but the *current* mutation's data/variables. + const mutateOptions = this.#mutateOptions + if (mutateOptions && this.hasListeners()) { + const variables = this.#currentResult.variables! + const onMutateResult = this.#currentResult.context + + const context = { + client: this.#client, + meta: this.options.meta, + mutationKey: this.options.mutationKey, + } satisfies MutationFunctionContext + + if (action?.type === 'success') { + try { + mutateOptions.onSuccess?.( + action.data, + variables, + onMutateResult, + context, + ) + } catch (e) { + void Promise.reject(e) + } + try { + mutateOptions.onSettled?.( + action.data, + null, + variables, + onMutateResult, + context, + ) + } catch (e) { + void Promise.reject(e) + } + } else if (action?.type === 'error') { + try { + mutateOptions.onError?.( + action.error, + variables, + onMutateResult, + context, + ) + } catch (e) { + void Promise.reject(e) + } + try { + mutateOptions.onSettled?.( + undefined, + action.error, + variables, + onMutateResult, + context, + ) + } catch (e) { + void Promise.reject(e) + } + } + } + + // Then trigger the listeners + this.listeners.forEach((listener) => { + listener(this.#currentResult) + }) + }) + } +} diff --git a/packages/react-query-pluggable/src/runtime/notifyManager.ts b/packages/react-query-pluggable/src/runtime/notifyManager.ts new file mode 100644 index 00000000000..f7e49b01d06 --- /dev/null +++ b/packages/react-query-pluggable/src/runtime/notifyManager.ts @@ -0,0 +1,127 @@ +type BatchCallsCallback> = (...args: T) => void + +type NotifyCallback = () => void + +type NotifyFunction = (callback: () => void) => void + +type ScheduleFunction = (callback: () => void) => void + +/** + * Default scheduling function used by the notify manager. + * Schedules the callback in a microtask with `queueMicrotask`. + */ +export const defaultScheduler: ScheduleFunction = queueMicrotask + +/** + * Creates a notify manager, which schedules and batches notifications to subscribers. Query uses a + * single instance of it, exported as {@link notifyManager}. + * @returns A new notify manager. + */ +export function createNotifyManager() { + let queue: Array = [] + let transactions = 0 + let notifyFn: NotifyFunction = (callback) => { + callback() + } + let scheduleFn = defaultScheduler + + const schedule = (callback: NotifyCallback): void => { + if (transactions) { + queue.push(callback) + } else { + scheduleFn(() => { + notifyFn(callback) + }) + } + } + const flush = (): void => { + const originalQueue = queue + queue = [] + if (originalQueue.length) { + scheduleFn(() => { + originalQueue.forEach((callback) => { + notifyFn(callback) + }) + }) + } + } + + return { + /** + * Batches all updates scheduled inside the passed callback. + * This is mainly used internally to optimize query client updating. + * Batches can be nested; the queue is only flushed once the outermost `batch` call finishes. + * The return value of `callback` is passed through. + * @param callback - The function to run in the batch. + * @returns The return value of `callback`. + */ + batch: (callback: () => T): T => { + let result + transactions++ + try { + result = callback() + } finally { + transactions-- + if (!transactions) { + flush() + } + } + return result + }, + /** + * All calls to the wrapped function will be batched. + * @param callback - The function to wrap. + * @returns A function that schedules a call to `callback` with the given arguments. + */ + batchCalls: >( + callback: BatchCallsCallback, + ): BatchCallsCallback => { + return (...args) => { + schedule(() => { + callback(...args) + }) + } + }, + /** + * Schedules a function to be run on the next batch. + * By default, the batch runs in a microtask. Use `setScheduler` to change when it runs. + */ + schedule, + /** + * Use this method to set a custom notify function. + * This can be used to for example wrap notifications with `React.act` while running tests. + * @param fn - Receives each notification callback and must call it. + */ + setNotifyFunction: (fn: NotifyFunction) => { + notifyFn = fn + }, + /** + * Configures a custom callback that schedules when the next batch runs. + * The default behavior is `queueMicrotask(callback)`. + * @param fn - Receives a callback that runs the next batch, and schedules it. + * @example + * ```ts + * import { notifyManager } from '@tanstack/react-query-pluggable' + * + * // Use the v5 timer-based scheduler + * notifyManager.setScheduler((cb) => setTimeout(cb, 0)) + * + * // Schedule batches before the next frame is rendered + * notifyManager.setScheduler(requestAnimationFrame) + * + * // Schedule batches some time in the future + * notifyManager.setScheduler((cb) => setTimeout(cb, 10)) + * ``` + */ + setScheduler: (fn: ScheduleFunction) => { + scheduleFn = fn + }, + } as const +} + +// SINGLETON + +/** + * Handles scheduling and batching callbacks in TanStack Query. + */ +export const notifyManager = createNotifyManager() diff --git a/packages/react-query-pluggable/src/runtime/placeholderData.ts b/packages/react-query-pluggable/src/runtime/placeholderData.ts new file mode 100644 index 00000000000..75a3530f771 --- /dev/null +++ b/packages/react-query-pluggable/src/runtime/placeholderData.ts @@ -0,0 +1,101 @@ +import { + replaceData, + shallowEqualObjects, +} from '@tanstack/query-core/primitives' +import { projectResult } from './projectResult' +import type { Query } from './query' +import type { + ProjectionFailure, + QueryObserverResultContext, +} from './queryObserver' +import type { QueryKey, QueryObserverOptionsBase } from './types' + +/* #__NO_SIDE_EFFECTS__ */ +/** + * Supplies temporary data while an observed query has no cached result. + * @param value - A placeholder value or a factory receiving the previous query and its data. + * @returns A query placeholder option. + */ +export function placeholderData( + value: TValue, +): readonly [typeof placeholderData, TValue] { + return [placeholderData, value] +} + +placeholderData.project = projectResult +placeholderData.resolve = resolvePlaceholder + +/** + * Reuses a pending query's placeholder until its factory, source query or sharing policy changes. + * @param options - Options that supply the placeholder. + * @param context - This observer or reader's cached placeholder. + * @param previousData - The previous data for structural sharing. + * @param previousQuery - The last observed query with defined data. + * @returns Placeholder data or the error thrown by its factory. + */ +function resolvePlaceholder< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey extends QueryKey, +>( + options: QueryObserverOptionsBase< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + context: QueryObserverResultContext< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + previousData: TData | undefined, + previousQuery: Query | undefined, +): QueryObserverResultContext< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey +>['placeholder'] { + const value = options.placeholderData![1] + const previousState = previousQuery?.state + const key: NonNullable['key'] = { + placeholderData: value, + structuralSharing: options.structuralSharing, + previousQuery, + previousState, + previousOptions: previousQuery?.options, + } + const memo = context.placeholder + if (shallowEqualObjects(key, memo?.key)) return memo + + let input: TQueryData | undefined + let sourceQuery: typeof previousQuery + let failure: ProjectionFailure | undefined + if (typeof value === 'function') { + try { + input = ( + value as unknown as ( + previous: TQueryData | undefined, + query: typeof previousQuery, + ) => TQueryData | undefined + )(previousState?.data, previousQuery) + } catch (error) { + failure = { error: error as TError, errorUpdatedAt: Date.now() } + } + if (previousState?.data !== undefined) sourceQuery = previousQuery + } else { + input = value + } + if (input !== undefined) + input = replaceData(previousData, input as unknown, options) as TQueryData + return input !== undefined || failure + ? { key, input, sourceQuery, failure } + : undefined +} diff --git a/packages/react-query-pluggable/src/runtime/projectResult.ts b/packages/react-query-pluggable/src/runtime/projectResult.ts new file mode 100644 index 00000000000..ecdf5182269 --- /dev/null +++ b/packages/react-query-pluggable/src/runtime/projectResult.ts @@ -0,0 +1,89 @@ +import type { Query, QueryState } from './query' +import type { QueryObserverResultContext } from './queryObserver' +import type { QueryKey, QueryObserverOptionsBase } from './types' + +/** + * Computes the data, status and error visible to one observer. + * @param query - The query whose cached data is being read. + * @param state - The query state for this read, including optimistic fetch state. + * @param options - The selection, placeholder and structural sharing options. + * @param context - Memoized results for this observer or uncommitted result reader. + * @param previousData - The preceding observer result for structural sharing. + * @param previousQuery - The preceding query with defined cached data. + * @returns The projected fields, including whether the result contains placeholder data. + */ +export function projectResult< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey extends QueryKey, +>( + query: Query, + state: QueryState, + options: QueryObserverOptionsBase< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + context: QueryObserverResultContext< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + previousData: TData | undefined, + previousQuery: Query | undefined, +): Pick< + QueryState, + 'data' | 'status' | 'error' | 'errorUpdatedAt' +> & { isPlaceholderData: boolean } { + context.project = projectResult + const { select, placeholderData } = options + context.placeholder = + state.data === undefined && state.status === 'pending' && placeholderData + ? placeholderData[0].resolve( + options, + context, + previousData, + previousQuery, + ) + : undefined + const placeholder = context.placeholder + const input = placeholder ? placeholder.input : state.data + // A previously selected query may have lost its data even if this render has no selector. + if ( + context.selected?.query && + context.selected.query.state.data === undefined + ) { + context.selected = undefined + if (!context.selection?.failure) context.selection = undefined + } + if (select && input !== undefined) { + select[0].resolve( + options, + select[1], + context, + previousData, + input, + placeholder ? placeholder.sourceQuery : query, + ) + } else { + context.selection = undefined + } + const failure = placeholder?.failure ?? context.selection?.failure + const isPlaceholderData = !!placeholder && input !== undefined && !failure + const { error, errorUpdatedAt } = failure ?? state + return { + data: context.selection + ? context.selected?.data + : (input as unknown as TData | undefined), + error, + errorUpdatedAt, + status: failure ? 'error' : isPlaceholderData ? 'success' : state.status, + isPlaceholderData, + } +} diff --git a/packages/react-query-pluggable/src/runtime/projectionTypes.ts b/packages/react-query-pluggable/src/runtime/projectionTypes.ts new file mode 100644 index 00000000000..856fb0dfc7f --- /dev/null +++ b/packages/react-query-pluggable/src/runtime/projectionTypes.ts @@ -0,0 +1,20 @@ +import type { placeholderData } from './placeholderData' +import type { select } from './select' + +/** A selector and its opt-in observer implementation. */ +export type Select = readonly [ + feature: typeof select, + value: (data: TInput) => TData, +] + +/** Placeholder data (or a factory) paired with its observer implementation. */ +export type PlaceholderData = readonly [ + feature: typeof placeholderData, + value: + // oxlint-disable-next-line typescript/no-unsafe-function-type -- excludes all callable and constructable values + | (TData extends Function ? never : TData) + | (( + previousData: TData | undefined, + previousQuery: TQuery | undefined, + ) => TData | undefined), +] diff --git a/packages/react-query-pluggable/src/runtime/queriesObserver.ts b/packages/react-query-pluggable/src/runtime/queriesObserver.ts new file mode 100644 index 00000000000..853e1ea15e2 --- /dev/null +++ b/packages/react-query-pluggable/src/runtime/queriesObserver.ts @@ -0,0 +1,476 @@ +import { + Subscribable, + replaceEqualDeep, + shallowEqualObjects, + shouldThrowError, +} from '@tanstack/query-core/primitives' +import { notifyManager } from './notifyManager' +import { defaultQueryOptions } from './queryClient' +import { QueryObserver } from './queryObserver' +import type { + QueriesObserverOptions, + QueriesObserverResultReader, + QueryObserverResultReader, +} from '@tanstack/query-core' +import type { QueryClient } from './queryClient' +import type { ObserverOptionsInput } from './queryObserver' +import type { + DefaultedQueryObserverOptions, + QueryObserverResult, +} from './types' + +type CombineContext = { + result?: Array + combine?: CombineFn + value?: TCombinedResult + queryHashes?: Array +} + +type CombineFn = ( + result: Array, +) => TCombinedResult + +type QueriesObserverListener = (result: Array) => void + +type QueryObserverMatch = { + defaultedQueryOptions: DefaultedQueryObserverOptions + observer: QueryObserver + reader?: QueryObserverResultReader +} + +/** + * Returns the items of `array1` that are not in `array2`. + * @param array1 - The items to filter. + * @param array2 - The items to exclude. + * @returns A new array with the items of `array1` that are not in `array2`. + */ +function difference(array1: Array, array2: Array): Array { + const excludeSet = new Set(array2) + return array1.filter((x) => !excludeSet.has(x)) +} + +/** + * Compares two arrays of results by position and field value. + * @param result - The new results. + * @param previous - The previous results, if available. + * @returns Whether the results match. + */ +function equalResults( + result: Array, + previous: Array | undefined, +): boolean { + return ( + !!previous && + result.length === previous.length && + result.every((value, index) => shallowEqualObjects(value, previous[index])) + ) +} + +/** + * A `QueriesObserver` watches an array of queries at once, exposing them as + * a single array of `QueryObserverResult`s (or, when a `combine` option is + * given, as a combined value derived from that array). It manages one + * internal `QueryObserver` per query, and is the primitive that framework + * adapters (e.g. `useQueries`) build their hooks on top of. + * @example + * ```ts + * const observer = new QueriesObserver(queryClient, [ + * { queryKey: ['post', 1], queryFn: fetchPost }, + * { queryKey: ['post', 2], queryFn: fetchPost }, + * ]) + * + * const unsubscribe = observer.subscribe((result) => { + * console.log(result) + * }) + * ``` + */ +export class QueriesObserver< + TCombinedResult = Array, +> extends Subscribable { + #client: QueryClient + #result: Array + #options?: QueriesObserverOptions + #observers: Array + #combinedResult?: TCombinedResult + #combineContext: CombineContext = {} + #observerMatches: Array = [] + #updatingQueries = false + + constructor( + client: QueryClient, + queries: Array>, + options?: QueriesObserverOptions, + ) { + super() + + this.#client = client + this.#options = options + this.#observers = [] + this.#result = [] + + this.setQueries(queries) + } + + protected override onSubscribe(): void { + if (this.listeners.size === 1) { + this.#observers.forEach((observer) => this.#subscribeTo(observer)) + } + } + + protected override onUnsubscribe(): void { + if (!this.listeners.size) { + this.destroy() + } + } + + /** + * Stops observing all queries: clears all listeners and destroys every + * underlying `QueryObserver` this observer manages. + */ + destroy(): void { + this.listeners = new Set() + this.#observers.forEach((observer) => { + observer.destroy() + }) + } + + /** + * Replaces the set of queries being observed. Existing `QueryObserver`s + * are reused for queries that match an already-observed query hash; + * observers for queries that are no longer present are destroyed, and new + * observers are created and subscribed to for newly added queries. + * @param queries - The options of the queries to observe. + * @param options - Replaces the observer's options, e.g. its `combine` function. + * @example + * ```ts + * observer.setQueries([ + * { queryKey: ['post', 1], queryFn: fetchPost }, + * { queryKey: ['post', 3], queryFn: fetchPost }, + * ]) + * ``` + */ + setQueries( + queries: Array, + options?: QueriesObserverOptions, + ): void { + this.#setQueries(this.#findMatchingObservers(queries), options) + } + + #setQueries( + newObserverMatches: Array, + options?: QueriesObserverOptions, + ): void { + this.#options = options + + if (process.env.NODE_ENV !== 'production') { + const queryHashes = newObserverMatches.map( + (match) => match.defaultedQueryOptions.queryHash, + ) + if (new Set(queryHashes).size !== queryHashes.length) { + console.warn( + '[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior.', + ) + } + } + + notifyManager.batch(() => { + const prevObservers = this.#observers + + // Apply all options before combining or notifying with the new results. + this.#updatingQueries = true + try { + newObserverMatches.forEach((match) => { + if (match.reader) { + match.reader.commit() + } else { + match.observer.setOptions(match.defaultedQueryOptions) + } + }) + } finally { + this.#updatingQueries = false + } + + const newObservers = newObserverMatches.map((match) => match.observer) + const newResult = newObservers.map((observer) => + observer.getCurrentResult(), + ) + + const hasStructuralChange = + prevObservers.length !== newObservers.length || + newObservers.some( + (observer, index) => observer !== prevObservers[index], + ) + + if (!hasStructuralChange && equalResults(newResult, this.#result)) return + + if (hasStructuralChange) { + this.#observerMatches = newObserverMatches.map( + ({ defaultedQueryOptions, observer }) => ({ + defaultedQueryOptions, + observer, + }), + ) + this.#observers = newObservers + } + + this.#result = newResult + + if (!this.hasListeners()) return + + if (hasStructuralChange) { + difference(prevObservers, newObservers).forEach((observer) => { + observer.destroy() + }) + difference(newObservers, prevObservers).forEach((observer) => + this.#subscribeTo(observer), + ) + } + + this.#notify() + }) + } + + /** + * Returns the most recently computed array of `QueryObserverResult`s, one + * per observed query, in the same order as the queries passed to the + * constructor or `setQueries`. + * @returns The current results. + * @example + * ```ts + * const results = observer.getCurrentResult() + * const data = results.map((result) => result.data) + * ``` + */ + getCurrentResult(): Array { + return this.#result + } + + /** + * Returns the underlying `QueryObserver` instances this observer manages, + * in the same order as the queries passed to the constructor or + * `setQueries`. + * @returns The managed query observers. + */ + getObservers() { + return this.#observers + } + + /** + * Creates a reader for the supplied queries and combine function. Reads keep + * result and combine caches local until commit applies the queries and reuses + * their computation state. Abandoned readers do not change active observers. + * @param queries - The options of the queries to read and commit. + * @param options - The combine function used for this reader. + * @returns A reader with local snapshot and combine caches. + */ + createResultReader( + queries: Array>, + options?: QueriesObserverOptions, + ): QueriesObserverResultReader { + const matches = this.#findMatchingObservers(queries).map((match) => ({ + ...match, + reader: match.observer.createResultReader(match.defaultedQueryOptions), + })) + const queryHashes = matches.map( + (match) => match.defaultedQueryOptions.queryHash, + ) + const combine = options?.combine + const context = { ...this.#combineContext } + let result = this.#result + + const getSnapshot = () => { + const nextResult = matches.map((match) => match.reader.getSnapshot()) + if (!shallowEqualObjects(nextResult, result)) { + result = nextResult + } + return result + } + + return { + getSnapshot, + combineResult: (input) => { + // Notifications may have already combined these results. + const committed = this.#combineContext + if ( + committed.combine === combine && + equalResults(input, committed.result) && + shallowEqualObjects(queryHashes, committed.queryHashes) + ) { + Object.assign(context, committed) + } + return this.#combineResult( + this.#trackResult(input, matches), + combine, + queryHashes, + context, + input, + ) + }, + commit: () => { + this.#combineContext = { ...context } + this.#setQueries(matches, { combine }) + if ( + this.#options?.combine === combine && + equalResults(this.#result, context.result) + ) { + this.#combinedResult = context.value + } + }, + } + } + + #trackResult( + result: Array, + matches: Array, + ) { + const trackedProps = new Set() + + return matches.map((match, index) => { + const observerResult = result[index]! + return !match.defaultedQueryOptions.notifyOnChangeProps + ? match.observer.trackResult(observerResult, (accessedProp) => { + // track property on all observers to ensure proper (synchronized) tracking (#7000) + if (!trackedProps.has(accessedProp)) { + trackedProps.add(accessedProp) + matches.forEach((m) => { + m.observer.trackProp(accessedProp) + }) + } + }) + : observerResult + }) + } + + #combineResult( + input: Array, + combine: CombineFn | undefined, + queryHashes?: Array, + context = this.#combineContext, + result = this.#result, + ): TCombinedResult { + if (combine) { + const queryHashesChanged = + queryHashes !== undefined && + context.queryHashes !== undefined && + !shallowEqualObjects(queryHashes, context.queryHashes) + + if ( + !equalResults(result, context.result) || + queryHashesChanged || + combine !== context.combine + ) { + context.value = replaceEqualDeep(context.value, combine(input)) + context.combine = combine + context.result = result + if (queryHashes !== undefined) { + context.queryHashes = queryHashes + } + } + + return context.value as TCombinedResult + } + return input as any + } + + #shouldSkipCombine(): boolean { + return ( + !this.#options?.combine || + this.#observers.some((observer, index) => { + const result = this.#result[index] + return ( + (observer.options.suspense && result?.data === undefined) || + (!!result?.isError && + !result.isFetching && + shouldThrowError(observer.options.throwOnError, [ + result.error, + observer.getCurrentQuery(), + ])) + ) + }) + ) + } + + #findMatchingObservers( + queries: Array, + ): Array { + const prevObserversMap = new Map>() + + this.#observers.forEach((observer) => { + const key = observer.options.queryHash + if (!key) return + + const previousObservers = prevObserversMap.get(key) + + if (previousObservers) { + previousObservers.push(observer) + } else { + prevObserversMap.set(key, [observer]) + } + }) + + const observers: Array = [] + + queries.forEach((options) => { + const defaultedOptions = defaultQueryOptions(this.#client, options) + const match = prevObserversMap.get(defaultedOptions.queryHash)?.shift() + const observer = + match ?? new QueryObserver(this.#client, defaultedOptions) + + observers.push({ + defaultedQueryOptions: defaultedOptions, + observer, + }) + }) + + return observers + } + + #subscribeTo(observer: QueryObserver): void { + // Create the listener here, not in `setQueries`: a listener created there + // keeps the previous observers, and their queries, alive (#12656) + observer.subscribe((result) => { + this.#onUpdate(observer, result) + }) + } + + #onUpdate(observer: QueryObserver, result: QueryObserverResult): void { + if (this.#updatingQueries) return + + const index = this.#observers.indexOf(observer) + if (index !== -1) { + this.#result = this.#result.slice() + this.#result[index] = result + this.#notify() + } + } + + #notify(): void { + if (this.hasListeners()) { + const shouldSkipCombine = this.#shouldSkipCombine() + const previousResult = this.#combinedResult + const newResult = shouldSkipCombine + ? previousResult + : this.#combineResult( + this.#trackResult(this.#result, this.#observerMatches), + this.#options?.combine, + this.#observerMatches.map( + (match) => match.defaultedQueryOptions.queryHash, + ), + ) + + this.#combinedResult = newResult + if (shouldSkipCombine || previousResult !== newResult) { + notifyManager.batch(() => { + this.listeners.forEach((listener) => { + listener(this.#result) + }) + }) + } + } + } +} + +export type { + QueriesObserverResultReader, + QueriesObserverOptions, +} from '@tanstack/query-core' diff --git a/packages/react-query-pluggable/src/runtime/query.ts b/packages/react-query-pluggable/src/runtime/query.ts new file mode 100644 index 00000000000..ee440535082 --- /dev/null +++ b/packages/react-query-pluggable/src/runtime/query.ts @@ -0,0 +1,837 @@ +import { + CancelledError, + Removable, + createRetryer, + fetchSignal, + fetchState, + getDefaultQueryState, + noop, + replaceData, + skipToken, + successState, + timeUntilStale, +} from '@tanstack/query-core/primitives' +import { notifyManager } from './notifyManager' +import { getQueryCache } from './queryClient' +import { ensureQueryFn, resolveQueryValue } from './utils' +import type { QueryState } from '@tanstack/query-core' +import type { + FetchOptions, + QueryAction, + Retryer, +} from '@tanstack/query-core/primitives' +import type { prepareInfiniteFetch } from './infiniteQueryBehavior' +import type { QueryCache } from './queryCache' +import type { QueryClient } from './queryClient' +import type { QueryObserver } from './queryObserver' +import type { + CancelOptions, + DefaultError, + QueryKey, + QueryMeta, + QueryOptions, + SetDataOptions, + StaleTime, +} from './types' + +interface QueryConfig< + TQueryFnData, + TError, + TData, + TQueryKey extends QueryKey = QueryKey, +> { + client: QueryClient + queryKey: TQueryKey + queryHash: string + options?: QueryOptions + defaultOptions?: QueryOptions + state?: QueryState +} + +/** + * The context passed to a {@link QueryBehavior}'s `onFetch`, which can replace `fetchFn` to change + * how the query fetches (e.g. to fetch pages for an infinite query). + */ +export interface FetchContext< + TQueryFnData, + TError, + TData, + TQueryKey extends QueryKey = QueryKey, +> { + /** + * The function that runs the fetch. By default it calls `queryFn`; `onFetch` can replace it. + */ + fetchFn: () => unknown | Promise + /** + * The options of this fetch. + */ + fetchOptions?: FetchOptions + /** + * The `AbortSignal` that aborts when the fetch is cancelled. + */ + signal: AbortSignal + /** + * The options of the query. + */ + options: QueryOptions + /** + * The `QueryClient` the query belongs to. + */ + client: QueryClient + /** + * The key of the query. + */ + queryKey: TQueryKey + /** + * The state of the query when the fetch starts. + */ + state: QueryState +} + +/** + * Customizes how a query fetches, e.g. the behavior that fetches the pages of an infinite query. + */ +export interface QueryBehavior< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> { + /** + * Called before each fetch of the query, e.g. to replace `fetchFn` in the context. + */ + onFetch: ( + context: FetchContext, + query: Query, + ) => void +} + +// CLASS + +/** + * Represents a single cached query. A `Query` holds the query's key, options, + * state (data/error/status), and the observers currently subscribed to it. + * + * Instances are created and managed internally by `QueryCache`; application + * code typically interacts with queries indirectly through `QueryClient` or + * a framework hook like `useQuery`. Direct access to a `Query` instance is + * possible via `queryCache.find()`/`findAll()` for inspecting cache state. + * @example + * ```ts + * const queryCache = getQueryCache(queryClient) + * const query = queryCache.find({ queryKey: ['posts'] }) + * + * if (query) { + * console.log(query.state.dataUpdatedAt) + * } + * ``` + */ +export class Query< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> extends Removable { + queryKey: TQueryKey + queryHash: string + options!: QueryOptions + state: QueryState + #prepareInfiniteFetch?: typeof prepareInfiniteFetch + + #initialState: QueryState + #revertState?: QueryState + #cache: QueryCache + #client: QueryClient + #retryer?: Retryer + #fetchPromise?: Promise + observers: Array> + #defaultOptions?: QueryOptions + #abortSignalConsumed: boolean + + constructor(config: QueryConfig) { + super() + + this.#abortSignalConsumed = false + this.#defaultOptions = config.defaultOptions + this.setOptions(config.options) + this.observers = [] + this.#client = config.client + this.#cache = getQueryCache(this.#client) + this.queryKey = config.queryKey + this.queryHash = config.queryHash + this.#initialState = getDefaultQueryState(this.options) + this.state = config.state ?? this.#initialState + this.scheduleGc() + } + /** + * The `meta` object passed in the query's options, if any. + * @returns The query's `meta`, or `undefined` if none was set. + */ + get meta(): QueryMeta | undefined { + return this.options.meta + } + + /** + * `'infinite'` for an infinite query, otherwise `undefined`. + * @internal + * @returns The type of the query, determined by its page fetcher. + */ + get queryType(): 'infinite' | undefined { + return this.#prepareInfiniteFetch ? 'infinite' : undefined + } + + /** + * The promise for the currently in-flight fetch, if the query is fetching. + * `undefined` when the query is not fetching. + * @returns The promise of the in-flight fetch, or `undefined`. + */ + get promise(): Promise | undefined { + return this.#retryer?.promise + } + + /** + * Replaces the query's options and applies their `gcTime`. If the query has no data yet, it gets + * the `initialData` from the new options, if any. + * @internal + * @param options - The new query options, merged on top of the query's default options. + */ + setOptions( + options?: QueryOptions, + ): void { + this.options = { ...this.#defaultOptions, ...options } + + const internalOptions = options as + | { _prepareInfiniteFetch?: typeof prepareInfiniteFetch } + | undefined + this.#prepareInfiniteFetch ??= internalOptions?._prepareInfiniteFetch + + this.updateGcTime(this.options.gcTime) + + // oxlint-disable-next-line typescript/no-unnecessary-condition -- the constructor calls 'setOptions' before it assigns 'state' + if (this.state && this.state.data === undefined) { + const defaultState = getDefaultQueryState(this.options) + if (defaultState.data !== undefined) { + this.setState( + successState(defaultState.data, defaultState.dataUpdatedAt), + ) + this.#initialState = defaultState + } + } + } + + protected override optionalRemove() { + if (!this.observers.length && this.state.fetchStatus === 'idle') { + this.#cache.remove(this) + } + } + + /** + * Writes new data to the query and marks it as successfully fetched. + * @internal + * @param newData - The data to write. Structural sharing with the current data is applied. + * @param options - Set `updatedAt` to override the timestamp, and `manual` to mark the write as + * manual (e.g. from `setQueryData`). + * @returns The data that was written. + */ + setData( + newData: TData, + options?: SetDataOptions & { manual: boolean }, + ): TData { + const data = replaceData(this.state.data, newData, this.options) + + const manual = options?.manual + const dataUpdatedAt = options?.updatedAt + this.state = { + ...this.state, + ...successState(data, dataUpdatedAt), + dataUpdateCount: this.state.dataUpdateCount + 1, + ...(!manual && { + fetchStatus: 'idle' as const, + fetchFailureCount: 0, + fetchFailureReason: null, + }), + } + // A manual write becomes the snapshot to restore if a fetch is cancelled. + this.#revertState = manual ? this.state : undefined + this.#notify({ type: 'success', data, dataUpdatedAt, manual }) + + return data + } + + /** + * Merges the given partial state directly into this query's state, notifying observers. Used + * by persistence and broadcast plugins to restore a state snapshot, and by devtools to let a + * user manually trigger a loading/error state or edit the cached data. + * @param state - The partial state to merge into the query's state. + */ + setState(state: Partial>): void { + this.#update(state, { type: 'setState', state }) + } + + /** + * Cancels the query's currently in-flight fetch, if any. + * - Returns a promise that resolves once the cancellation has settled. + * - If no fetch is in progress, resolves immediately. + * @param options - Set `revert` to restore the state from before the fetch started, and `silent` + * to suppress the cancellation error when a new fetch replaces the cancelled one. + * @returns A promise that resolves once the cancellation has settled. + * @example + * ```ts + * await query.cancel() + * ``` + */ + cancel(options?: CancelOptions): Promise { + const promise = this.#retryer?.promise + this.#retryer?.cancel(options) + return promise ? promise.then(noop, noop) : Promise.resolve() + } + + /** + * Silently cancels any in-flight fetch, then clears the query's garbage + * collection timeout. Called by `QueryCache` when the query is removed from + * the cache. + * @see {@link Query#cancel} + */ + override destroy(): void { + this.cancel({ silent: true }) + // An abort listener can unsubscribe and schedule GC during cancellation. + super.destroy() + } + + /** + * The state the query was created with. + * @internal + * @returns The state the query had when it was first created, used by {@link Query#reset}. + */ + get resetState(): QueryState { + return this.#initialState + } + + /** + * Resets the query back to its initial state (the state it had when it was + * first created, e.g. any `initialData`), destroying it first to cancel any + * in-flight fetch. + */ + reset(): void { + this.destroy() + this.setState(this.resetState) + } + + /** + * Returns `true` if the query has at least one observer for which `enabled` + * does not resolve to `false`. + * @returns `true` if the query has an enabled observer. + */ + isActive(): boolean { + return this.observers.some( + (observer) => resolveQueryValue(observer.options.enabled, this) !== false, + ) + } + + /** + * Returns `true` if the query is disabled, meaning it will not fetch + * automatically. + * - If the query has observers, it is disabled when none of them are active + * (see `isActive`). + * - If the query has no observers, it is disabled when its `queryFn` is + * `skipToken` or it has never been fetched. + * @returns `true` if the query is disabled. + */ + isDisabled(): boolean { + if (this.getObserversCount() > 0) { + return !this.isActive() + } + // if a query has no observers, it should still be considered disabled if it never attempted a fetch + return this.options.queryFn === skipToken || !this.isFetched() + } + + /** + * Returns `true` if the query has been fetched, i.e. it has resolved with + * either data or an error at least once. + * @returns `true` if the query has been fetched. + */ + isFetched() { + return this.state.dataUpdateCount + this.state.errorUpdateCount > 0 + } + + /** + * Returns `true` if the query has data and at least one observer configured with + * `staleTime: 'static'`, meaning it is treated as never stale. + * @returns `true` if the query is static. + */ + isStatic(): boolean { + if (this.state.data === undefined) { + return false + } + + if (this.getObserversCount() > 0) { + return this.observers.some( + (observer) => + resolveQueryValue(observer.options.staleTime, this) === 'static', + ) + } + + return false + } + + /** + * Returns `true` if the query is stale. + * - If the query has observers, defers to whether any observer's current + * result reports `isStale` (which accounts for each observer's own + * `staleTime` and `enabled` state). + * - If the query has no observers, it is considered stale when it has no + * data or has been invalidated. + * @returns `true` if the query is stale. + * @see {@link Query#isStaleByTime} + * @example + * ```ts + * if (query.isStale()) { + * // refetch or otherwise treat the cached data as outdated + * } + * ``` + */ + isStale(): boolean { + // check observers first, their `isStale` has the source of truth + // calculated with `isStaleByTime` and it takes `enabled` into account + if (this.getObserversCount() > 0) { + return this.observers.some( + (observer) => observer.getCurrentResult().isStale, + ) + } + + return this.state.data === undefined || this.state.isInvalidated + } + + /** + * Returns `true` if the query's data is stale relative to the given + * `staleTime` (defaults to `0`). + * - A query with no data is always stale. + * - `staleTime: 'static'` is never stale. + * - An invalidated query is always stale. + * - Otherwise, staleness is based on elapsed time since `dataUpdatedAt`. + * @param staleTime - The time, in milliseconds, after which data is considered stale, or + * `'static'` to never treat existing data as stale. A query without data is stale either way. + * @returns `true` if the query's data is stale. + * @see {@link Query#isStale} + * @example + * ```ts + * const isStale = query.isStaleByTime(60 * 1000) + * ``` + */ + isStaleByTime(staleTime: StaleTime = 0): boolean { + // no data is always stale + if (this.state.data === undefined) { + return true + } + // static is never stale + if (staleTime === 'static') { + return false + } + // if the query is invalidated, it is stale + if (this.state.isInvalidated) { + return true + } + + return !timeUntilStale(this.state.dataUpdatedAt, staleTime) + } + + /** + * Refetches the query when the window regains focus, if an observer wants that, and continues a + * paused fetch. + * @internal + */ + onFocus(): void { + const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus()) + + observer?.refetch({ cancelRefetch: false }) + + // Continue fetch if currently paused + this.#retryer?.continue() + } + + /** + * Refetches the query when the app reconnects, if an observer wants that, and continues a paused + * fetch. + * @internal + */ + onOnline(): void { + const observer = this.observers.find((x) => x.shouldFetchOnReconnect()) + + observer?.refetch({ cancelRefetch: false }) + + // Continue fetch if currently paused + this.#retryer?.continue() + } + + /** + * Subscribes an observer to the query and stops its garbage collection. + * @internal + * @param observer - The observer to add. Adding an observer that is already subscribed does + * nothing. + */ + addObserver(observer: QueryObserver): void { + if (!this.observers.includes(observer)) { + this.observers.push(observer) + + // Stop the query from being garbage collected + this.clearGcTimeout() + + this.#cache.notify({ type: 'observerAdded', query: this, observer }) + } + } + + /** + * Unsubscribes an observer from the query. + * @internal + * @param observer - The observer to remove. When the last observer is removed, the in-flight + * fetch is cancelled if its abort signal was consumed (otherwise only its retries are stopped), + * and garbage collection is scheduled if the query is still in the cache. + */ + removeObserver(observer: QueryObserver): void { + const index = this.observers.indexOf(observer) + if (index !== -1) { + this.observers.splice(index, 1) + + if (!this.observers.length) { + // If the transport layer does not support cancellation + // we'll let the query continue so the result can be cached + if (this.#retryer) { + if ( + this.#abortSignalConsumed || + (this.state.fetchStatus === 'paused' && + this.state.status === 'pending') + ) { + this.#retryer.cancel({ revert: true }) + } else { + this.#retryer.cancelRetry() + } + } + + this.#scheduleGcIfCached() + } + + this.#cache.notify({ type: 'observerRemoved', query: this, observer }) + } + } + + /** + * Returns the number of observers currently subscribed to this query. + * @returns The number of observers. + * @example + * ```ts + * if (query.getObserversCount() === 0) { + * // no component is currently watching this query + * } + * ``` + */ + getObserversCount(): number { + return this.observers.length + } + + /** + * Marks the query as invalidated, unless it is already invalidated. This + * updates `state.isInvalidated` and notifies observers, but does not by + * itself trigger a refetch. + * @example + * ```ts + * query.invalidate() + * ``` + */ + invalidate(): void { + if (!this.state.isInvalidated) { + this.#update({ isInvalidated: true }, { type: 'invalidate' }) + } + } + + /** + * Fetches the query, i.e. runs its `queryFn` (through any configured + * retryer/behavior) and updates the query's state with the result. + * - If a fetch is already in flight, returns its promise instead of + * starting a new one, unless `fetchOptions.cancelRefetch` is set and the + * query already has data, in which case the current fetch is silently + * cancelled first. + * - If `options` is passed, it replaces the query's current options + * before fetching. + * @param options - Query options that replace the query's current options before fetching. They + * are not applied when an in-flight fetch is reused. + * @param fetchOptions - Set `cancelRefetch` to cancel an in-flight fetch first (only if the query + * already has data), and `meta` to pass extra information to the query's behavior. + * @returns A promise that resolves with the fetched data, or rejects with the fetch error. If the + * fetch is cancelled with `revert` while the query has data, it resolves with the restored data + * instead. + */ + async fetch( + options?: QueryOptions, + fetchOptions?: FetchOptions, + ): Promise { + if ( + this.state.fetchStatus !== 'idle' && + // If the promise in the retryer is already rejected, we have to definitely + // re-start the fetch; there is a chance that the query is still in a + // pending state when that happens + this.#retryer?.status() !== 'rejected' + ) { + if (this.state.data !== undefined && fetchOptions?.cancelRefetch) { + // Silently cancel current fetch if the user wants to cancel refetch + this.cancel({ silent: true }) + } else if (this.#retryer && this.#fetchPromise) { + // make sure that retries that were potentially cancelled due to unmounts can continue + this.#retryer.continueRetry() + // Return current promise if we are already fetching + return this.#fetchPromise + } + } + + // Update config if passed, otherwise the config from the last execution is used + if (options) { + this.setOptions(options) + } + + // Use the options from the first observer with a query function if no function is found. + // This can happen when the query is hydrated or created with setQueryData. + if (!this.options.queryFn) { + const observer = this.observers.find((x) => x.options.queryFn) + if (observer) { + this.setOptions(observer.options) + } + } + + if (process.env.NODE_ENV !== 'production') { + if (!Array.isArray(this.options.queryKey)) { + console.error( + `As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']`, + ) + } + } + + const abortController = new AbortController() + + const addSignalProperty: ( + object: object, + ) => asserts object is { signal: AbortSignal } = (object) => { + Object.defineProperties(object, { + [fetchSignal]: { value: abortController.signal, enumerable: true }, + signal: { + enumerable: true, + get: () => { + this.#abortSignalConsumed = true + return abortController.signal + }, + }, + }) + } + + // Create fetch function + const fetchFn = () => { + const queryFn = ensureQueryFn(this.options, fetchOptions) + + const queryFnContext = { + client: this.#client, + queryKey: this.queryKey, + meta: this.meta, + } + addSignalProperty(queryFnContext) + + this.#abortSignalConsumed = false + if (this.options.persister) { + return this.options.persister( + queryFn, + queryFnContext, + this as unknown as Query, + ) + } + + return queryFn(queryFnContext) + } + + // Trigger behavior hook + const context = { + fetchOptions, + options: this.options, + queryKey: this.queryKey, + client: this.#client, + state: this.state, + fetchFn, + } + addSignalProperty(context) + + const prepare = this.#prepareInfiniteFetch as + | QueryBehavior['onFetch'] + | undefined + prepare?.(context, this as unknown as Query) + + // Store state in case the current fetch needs to be reverted + this.#revertState = this.state + + // Set to fetching state if not already in it + if ( + this.state.fetchStatus === 'idle' || + this.state.fetchMeta !== context.fetchOptions?.meta + ) { + const meta = context.fetchOptions?.meta + this.#update( + { + ...fetchState(this.state.data, this.options), + fetchMeta: meta ?? null, + }, + { type: 'fetch', meta }, + ) + } + + // Try to fetch the data + const retryer = (this.#retryer = createRetryer({ + initialPromise: fetchOptions?.initialPromise as + | Promise + | undefined, + fn: context.fetchFn as () => Promise, + onCancel: (error) => { + if (error instanceof CancelledError && error.revert) { + this.setState({ + ...this.#revertState, + fetchStatus: 'idle' as const, + }) + } + abortController.abort() + }, + onFail: (failureCount, error) => { + this.#update( + { fetchFailureCount: failureCount, fetchFailureReason: error }, + { type: 'failed', failureCount, error }, + ) + }, + onPause: () => { + this.#update({ fetchStatus: 'paused' }, { type: 'pause' }) + }, + onContinue: () => { + this.#update({ fetchStatus: 'fetching' }, { type: 'continue' }) + }, + retry: context.options.retry, + retryDelay: context.options.retryDelay, + networkMode: context.options.networkMode, + canRun: () => true, + })) + + const fetchPromise = (async () => { + try { + const data = await retryer.promise + // this is more of a runtime guard + if (data === undefined) { + if (process.env.NODE_ENV !== 'production') { + console.error( + `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`, + ) + } + throw new Error(`${this.queryHash} data is undefined`) + } + + this.setData(data) + + // Notify cache callback + this.#cache.config.onSuccess?.(data, this as Query) + this.#cache.config.onSettled?.( + data, + this.state.error as any, + this as Query, + ) + return data + } catch (error) { + if (error instanceof CancelledError) { + if (error.silent) { + if (this.#retryer !== retryer && this.#fetchPromise) { + // A new fetch replaced the silently cancelled one, + // so we piggyback onto that promise. + return this.#fetchPromise + } + throw error + } else if (error.revert) { + // transform error into reverted state data + // if the initial fetch was cancelled, we have no data, so we have + // to get reject with a CancelledError + if (this.state.data === undefined) { + throw error + } + return this.state.data + } + } + const fetchError = error as TError + this.#update( + { + error: fetchError, + errorUpdatedAt: Date.now(), + errorUpdateCount: this.state.errorUpdateCount + 1, + fetchFailureCount: this.state.fetchFailureCount + 1, + fetchFailureReason: fetchError, + fetchStatus: 'idle', + status: 'error', + isInvalidated: true, + }, + { type: 'error', error: fetchError }, + ) + + // Notify cache callback + this.#cache.config.onError?.( + error as any, + this as Query, + ) + this.#cache.config.onSettled?.( + this.state.data, + error as any, + this as Query, + ) + + throw error // rethrow the error for further handling + } finally { + // The settled retryer's promise would otherwise pin this fetch's raw + // result (a second copy after structural sharing) for the query's lifetime + if (this.#retryer === retryer) { + this.#retryer = undefined + this.#fetchPromise = undefined + } + this.#scheduleGcIfCached() + } + })() + this.#fetchPromise = fetchPromise + retryer.start() + return fetchPromise + } + + #scheduleGcIfCached(): void { + if ( + this.#cache.get( + this.queryHash, + ) === this + ) { + this.scheduleGc() + } + } + + #update( + state: Partial>, + action: QueryAction, + ): void { + this.state = { ...this.state, ...state } + this.#notify(action) + } + + #notify(action: QueryAction): void { + notifyManager.batch(() => { + // Keep the current iteration stable if an observer unsubscribes + // synchronously while it is being notified. + this.observers.slice().forEach((observer) => { + observer.onQueryUpdate() + }) + + this.#cache.notify({ query: this, type: 'updated', action }) + }) + } +} + +export type { QueryState } from '@tanstack/query-core' +export type { + FetchDirection, + FetchMeta, + FetchOptions, + QueryAction as Action, +} from '@tanstack/query-core/primitives' + +export { fetchState } from '@tanstack/query-core/primitives' diff --git a/packages/react-query-pluggable/src/runtime/queryCache.ts b/packages/react-query-pluggable/src/runtime/queryCache.ts new file mode 100644 index 00000000000..7af03876b43 --- /dev/null +++ b/packages/react-query-pluggable/src/runtime/queryCache.ts @@ -0,0 +1,401 @@ +import { Subscribable, hashKeyByOptions } from '@tanstack/query-core/primitives' +import { notifyManager } from './notifyManager' +import { Query } from './query' +import { defaultQueryOptions, getQueryDefaults } from './queryClient' +import { matchQuery } from './utils' +import type { CacheKeyConfig, NotifyEvent } from '@tanstack/query-core' +import type { QueryAction } from '@tanstack/query-core/primitives' +import type { QueryState } from './query' +import type { QueryClient } from './queryClient' +import type { QueryObserver } from './queryObserver' +import type { + DefaultError, + QueryKey, + QueryOptions, + WithRequired, +} from './types' +import type { QueryFilters } from './utils' + +/** + * Global callbacks that fire for every query handled by a `QueryCache`, regardless of which + * component or observer triggered it. Unlike `QueryClient`'s `defaultOptions`, which a query can + * override, these callbacks are always called. Unlike `MutationCacheConfig`'s callbacks, these + * are fire-and-forget: their return value is not awaited before the query settles. + */ +export interface QueryCacheConfig { + /** + * Configures query key comparison and hashing globally. + * `equalityFn` compares individual values during partial matching and defaults to strict equality. + * `hashFn` hashes query keys and defaults to `hashKey`. + */ + queryKey?: CacheKeyConfig + /** Called when any query in the cache encounters an error. */ + onError?: ( + error: DefaultError, + query: Query, + ) => void + /** Called when any query in the cache is successful. */ + onSuccess?: (data: unknown, query: Query) => void + /** Called when any query in the cache is settled, either successfully or with an error. */ + onSettled?: ( + data: unknown | undefined, + error: DefaultError | null, + query: Query, + ) => void +} + +/** + * The event passed to a `QueryCache` subscriber. Fired whenever a query is added or removed from + * the cache, its state is updated (e.g. via `query.setState` or `removeQueries`), or + * one of its observers is added, removed, or has its results or options updated. + */ +export type QueryCacheNotifyEvent = + | NotifyEventQueryAdded + | NotifyEventQueryRemoved + | NotifyEventQueryUpdated + | NotifyEventQueryObserverAdded + | NotifyEventQueryObserverRemoved + | NotifyEventQueryObserverResultsUpdated + | NotifyEventQueryObserverOptionsUpdated + +type QueryCacheListener = (event: QueryCacheNotifyEvent) => void + +/** + * The store a `QueryCache` keeps its queries in, keyed by query hash. + */ +export interface QueryStore { + /** + * Returns whether a query with the given hash is stored. + */ + has: (queryHash: string) => boolean + /** + * Stores a query under its hash. + */ + set: (queryHash: string, query: Query) => void + /** + * Returns the query with the given hash, if any. + */ + get: (queryHash: string) => Query | undefined + /** + * Removes the query with the given hash. + */ + delete: (queryHash: string) => void + /** + * Returns an iterator over all stored queries. + */ + values: () => IterableIterator +} + +interface NotifyEventQueryAdded extends NotifyEvent { + type: 'added' + query: Query +} + +interface NotifyEventQueryRemoved extends NotifyEvent { + type: 'removed' + query: Query +} + +interface NotifyEventQueryUpdated extends NotifyEvent { + type: 'updated' + query: Query + action: QueryAction +} + +interface NotifyEventQueryObserverAdded extends NotifyEvent { + type: 'observerAdded' + query: Query + observer: QueryObserver +} + +interface NotifyEventQueryObserverRemoved extends NotifyEvent { + type: 'observerRemoved' + query: Query + observer: QueryObserver +} + +interface NotifyEventQueryObserverResultsUpdated extends NotifyEvent { + type: 'observerResultsUpdated' + query: Query +} + +interface NotifyEventQueryObserverOptionsUpdated extends NotifyEvent { + type: 'observerOptionsUpdated' + query: Query + observer: QueryObserver +} + +// CLASS + +/** + * The `QueryCache` is the storage mechanism for TanStack Query. It stores all the data, meta + * information, and state of the queries it contains. + * + * Normally, you will not interact with the `QueryCache` directly and instead use a `QueryClient` + * for a specific cache. You can subscribe to it (inherited from `Subscribable`) to be informed of + * safe/known updates to the cache, such as queries being added, removed, or updated — updates made + * outside of the cache's own tracked mechanisms (e.g. mutating a query's state object directly) do + * not notify subscribers. + * @example + * ```ts + * const unsubscribe = queryCache.subscribe((event) => { + * console.log(event.type, event.query) + * }) + * ``` + */ +export class QueryCache extends Subscribable { + #queries: QueryStore + + constructor(public config: QueryCacheConfig = {}) { + super() + this.#queries = new Map() + } + + /** + * Returns the existing `Query` instance for the given options' `queryKey`/`queryHash`, or + * builds and adds a new one to the cache if none exists yet. Used by framework adapters and + * plugins (e.g. broadcast/persistence) that need to get-or-create a `Query` directly, bypassing + * the reactive `QueryObserver` machinery. + * @param client - The client the query belongs to, used to default its options. + * @param options - The query options, including the `queryKey`. A new query is created with the + * options defaulted by {@link defaultQueryOptions}. + * @param state - The initial state of a newly created query, e.g. when hydrating. Ignored if the + * query already exists. + * @returns The existing or newly created query. + * @example + * ```ts + * const queryCache = getQueryCache(queryClient) + * + * const query = queryCache.build(queryClient, { + * queryKey: ['posts'], + * queryFn: fetchPosts, + * }) + * ``` + */ + build< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + >( + client: QueryClient, + options: WithRequired< + QueryOptions, + 'queryKey' + >, + state?: QueryState, + ): Query { + const queryKey = options.queryKey + const queryHash = + options.queryHash ?? hashKeyByOptions(queryKey, this.config.queryKey) + let query = this.get(queryHash) + + if (!query) { + query = new Query({ + client, + queryKey, + queryHash, + options: defaultQueryOptions(client, options), + state, + defaultOptions: getQueryDefaults(client, queryKey), + }) + this.add(query) + } + + return query + } + + /** + * Adds a query to the cache. + * @internal + * @param query - The query to add. If a query with the same hash is already cached, nothing + * happens. + */ + add(query: Query): void { + if (!this.#queries.has(query.queryHash)) { + this.#queries.set(query.queryHash, query) + + this.notify({ + type: 'added', + query, + }) + } + } + + /** + * Destroys the given `Query` and removes it from the cache, notifying subscribers with a + * `'removed'` event. A no-op if the query is no longer the one currently stored under its hash + * (e.g. it was already replaced). Used by plugins (e.g. the broadcast client) that mirror + * removals across `QueryCache` instances. + * @param query - The query to remove. + * @example + * ```ts + * const queryCache = getQueryCache(queryClient) + * const query = queryCache.find({ queryKey: ['posts'] }) + * + * if (query) { + * queryCache.remove(query) + * } + * ``` + */ + remove(query: Query): void { + const queryInMap = this.#queries.get(query.queryHash) + + if (queryInMap === query) { + query.destroy() + this.#queries.delete(query.queryHash) + this.notify({ type: 'removed', query }) + } + } + + /** + * Removes all queries from the cache. + * @example + * ```ts + * const queryCache = getQueryCache(queryClient) + * + * queryCache.clear() + * ``` + */ + clear(): void { + notifyManager.batch(() => { + this.getAll().forEach((query) => { + this.remove(query) + }) + }) + } + + /** + * Returns the `Query` instance stored under the given `queryHash`, or `undefined` if none + * exists. Unlike {@link QueryCache#find}, this looks up by the already-computed hash rather + * than by `QueryFilters`. Used by plugins (e.g. broadcast/hydration) that already have a hash + * to look up directly. + * @param queryHash - The hash of the query to look up. + * @returns The query stored under the hash, or `undefined`. + * @example + * ```ts + * const queryCache = getQueryCache(queryClient) + * const queryHash = hashKey(['posts']) + * + * const query = queryCache.get(queryHash) + * ``` + */ + get< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + >( + queryHash: string, + ): Query | undefined { + return this.#queries.get(queryHash) as + | Query + | undefined + } + + /** + * Returns all queries within the cache. + * @returns Every query in the cache. + * @example + * ```ts + * const queryCache = getQueryCache(queryClient) + * + * const queries = queryCache.getAll() + * ``` + */ + getAll(): Array { + return [...this.#queries.values()] + } + + /** + * A slightly more advanced method that can be used to get an existing query instance from the + * cache. This instance not only contains all the state for the query, but all of the instances, + * and underlying guts of the query as well. If the query does not exist, `undefined` is + * returned. + * + * This is not typically needed for most applications, but can come in handy when needing more + * information about a query in rare scenarios (e.g. looking at `query.state.dataUpdatedAt` to + * decide whether a query is fresh enough to be used as an initial value). + * @param filters - The filters to match, including the required `queryKey`. `exact` defaults to + * `true`. + * @returns The first matching query, or `undefined`. + * @see {@link QueryCache#findAll} + * @example + * ```ts + * const queryCache = getQueryCache(queryClient) + * + * const query = queryCache.find({ queryKey: ['posts'] }) + * ``` + */ + find( + filters: WithRequired, + ): Query | undefined { + const defaultedFilters = { exact: true, ...filters } + + return this.getAll().find((query) => + matchQuery(defaultedFilters, query, this.config.queryKey), + ) as Query | undefined + } + + /** + * An even more advanced method that can be used to get existing query instances from the cache + * that partially match a query key. If no queries match, an empty array is returned. + * + * This is not typically needed for most applications, but can come in handy when needing more + * information about queries in rare scenarios. + * @param filters - The filters to match. Without filters, every query is returned. + * @returns The matching queries. + * @see {@link QueryCache#find} + * @example + * ```ts + * const queryCache = getQueryCache(queryClient) + * + * const queries = queryCache.findAll({ queryKey: ['posts'] }) + * ``` + */ + findAll(filters: QueryFilters = {}): Array { + const queries = this.getAll() + return Object.keys(filters).length > 0 + ? queries.filter((query) => + matchQuery(filters, query, this.config.queryKey), + ) + : queries + } + + /** + * Notifies every cache listener of an event, in one batch. + * @internal + * @param event - The event passed to every listener. + */ + notify(event: QueryCacheNotifyEvent): void { + notifyManager.batch(() => { + this.listeners.forEach((listener) => { + listener(event) + }) + }) + } + + /** + * Calls {@link Query#onFocus} on every cached query, in one batch. + * @internal + */ + onFocus(): void { + notifyManager.batch(() => { + this.getAll().forEach((query) => { + query.onFocus() + }) + }) + } + + /** + * Calls {@link Query#onOnline} on every cached query, in one batch. + * @internal + */ + onOnline(): void { + notifyManager.batch(() => { + this.getAll().forEach((query) => { + query.onOnline() + }) + }) + } +} diff --git a/packages/react-query-pluggable/src/runtime/queryClient.ts b/packages/react-query-pluggable/src/runtime/queryClient.ts new file mode 100644 index 00000000000..b55f4fa76ec --- /dev/null +++ b/packages/react-query-pluggable/src/runtime/queryClient.ts @@ -0,0 +1,783 @@ +import { + defaultQueryFn, + focusManager, + functionalUpdate, + hashKeyByOptions, + onlineManager, + partialMatchKey, + skipToken, +} from '@tanstack/query-core/primitives' +import { QueryCache } from './queryCache' +import { resolveQueryValue } from './utils' +import type { Updater } from '@tanstack/query-core/primitives' +import type { MutationCache } from './mutationCache' +import type { QueryState } from './query' +import type { + CacheKeyConfig, + DefaultError, + DefaultOptions, + DefaultedQueryObserverOptions, + InferDataFromTag, + InferErrorFromTag, + MutationKey, + MutationObserverOptions, + MutationOptions, + OmitKeyof, + QueryClientConfig, + QueryExecuteOptions, + QueryKey, + QueryObserverOptionsBase, + QueryOptions, + SetDataOptions, +} from './types' +import type { MutationFilters, QueryFilters } from './utils' + +/** Options whose query function always executes. */ +export type WithoutSkipToken = Omit< + T, + 'queryFn' +> & { + queryFn?: Exclude +} + +type QueryDefaults = OmitKeyof, 'queryKey'> +type MutationDefaults = MutationOptions + +class KeyDefaults< + TKey extends ReadonlyArray, + TOptions extends object, +> { + #entries = new Map() + + set(key: TKey, options: TOptions, config?: CacheKeyConfig): void { + this.#entries.set(hashKeyByOptions(key, config), { key, options }) + } + + get(key: TKey, config?: CacheKeyConfig): Partial { + const result: Partial = {} + for (const entry of this.#entries.values()) { + if (partialMatchKey(key, entry.key, config?.equalityFn)) { + Object.assign(result, entry.options) + } + } + return result + } +} + +/** @internal */ +export const mutationCacheKey = Symbol.for( + '@tanstack/react-query-pluggable/mutationCache', +) + +const clientState = Symbol.for('@tanstack/react-query-pluggable/clientState') + +/** Holds the caches, defaults and subscriptions shared by this client's consumers. */ +export class QueryClient { + /** @internal */ + [mutationCacheKey]?: MutationCache + /** @internal */ + readonly [clientState]: { + queryCache: QueryCache + defaultOptions: DefaultOptions + queryDefaults?: KeyDefaults + mutationDefaults?: KeyDefaults + mountCount: number + unsubscribeFocus?: () => void + unsubscribeOnline?: () => void + } + + constructor(config: QueryClientConfig = {}) { + this[mutationCacheKey] = config.mutationCache + this[clientState] = { + queryCache: config.queryCache ?? new QueryCache(), + defaultOptions: config.defaultOptions ?? {}, + mountCount: 0, + } + } +} + +/** + * Called by a framework adapter's `QueryClientProvider`-equivalent when it mounts, to start + * listening for focus/online events and resume paused mutations. Ref-counted via an internal + * mount count, so nested or multiple providers sharing the same `QueryClient` don't tear down + * the shared listeners until the last one unmounts. + * @param client - The client whose subscriptions are managed. + */ +export function mountQueryClient(client: QueryClient): void { + client[clientState].mountCount++ + if (client[clientState].mountCount !== 1) return + + client[clientState].unsubscribeFocus = focusManager.subscribe( + async (focused) => { + if (focused) { + await resumePausedMutations(client) + client[clientState].queryCache.onFocus() + } + }, + ) + client[clientState].unsubscribeOnline = onlineManager.subscribe( + async (online) => { + if (online) { + await resumePausedMutations(client) + client[clientState].queryCache.onOnline() + } + }, + ) +} + +/** + * The inverse of {@link mountQueryClient} — called by a framework adapter's + * `QueryClientProvider`-equivalent when it unmounts. Only tears down the focus/online + * listeners once the mount count returns to `0`. + * @param client - The client whose subscriptions are managed. + */ +export function unmountQueryClient(client: QueryClient): void { + client[clientState].mountCount-- + if (client[clientState].mountCount !== 0) return + + client[clientState].unsubscribeFocus?.() + client[clientState].unsubscribeFocus = undefined + + client[clientState].unsubscribeOnline?.() + client[clientState].unsubscribeOnline = undefined +} + +/** + * Returns the number of queries in the cache that are currently fetching, optionally + * matching a set of filters. This includes background-fetching, loading new pages, and + * loading more infinite query results. + * @param client - The client that owns this operation. + * @param filters - Narrows down which fetching queries are counted. Without filters, every + * fetching query is counted. + * @returns The number of matching queries whose `fetchStatus` is `'fetching'`. + * @example + * ```ts + * if (isFetching(queryClient)) { + * console.log('At least one query is fetching!') + * } + * ``` + */ +export function isFetching( + client: QueryClient, + filters?: Omit, +): number { + return client[clientState].queryCache.findAll({ + ...filters, + fetchStatus: 'fetching', + }).length +} + +/** + * Returns the number of mutations in the cache that are currently pending, optionally + * matching a set of filters. + * @param client - The client that owns this operation. + * @param filters - Narrows down which pending mutations are counted. Without filters, every + * pending mutation is counted. + * @returns The number of matching mutations whose `status` is `'pending'`. + * @example + * ```ts + * if (isMutating(queryClient)) { + * console.log('At least one mutation is pending!') + * } + * ``` + */ +export function isMutating< + TMutationFilters extends MutationFilters = MutationFilters< + any, + any + >, +>( + client: QueryClient, + filters?: NoInfer>, +): number { + return ( + client[mutationCacheKey]?.findAll({ ...filters, status: 'pending' }) + .length ?? 0 + ) +} + +/** + * Imperative (non-reactive) way to retrieve data for a QueryKey. + * Should only be used in callbacks or functions where reading the latest data is necessary, e.g. for optimistic updates. + * + * Hint: Do not use this function inside a component, because it won't receive updates. + * Use `useQuery` to create a `QueryObserver` that subscribes to changes. + * @param client - The client that owns this operation. + * @param queryKey - The query key of the query to read. + * @returns The cached data for the query, or `undefined` if no query with this key has been observed yet. + * @see {@link getQueriesData} + */ +export function getQueryData< + TQueryFnData = unknown, + TTaggedQueryKey extends QueryKey = QueryKey, + TInferredQueryFnData = InferDataFromTag, +>( + client: QueryClient, + queryKey: TTaggedQueryKey, +): TInferredQueryFnData | undefined { + const options = defaultQueryOptions(client, { queryKey }) + + return client[clientState].queryCache.get( + options.queryHash, + )?.state.data +} + +/** + * Synchronous way to immediately update a query's cached data. If the updater (or the value + * passed) resolves to `undefined`, the cache is left untouched and no query is created; + * otherwise, if the query does not exist yet, it will be created. To update multiple queries + * at once by partially matching query keys, import `setQueriesData`. + * + * Updates must be performed immutably: do not mutate `oldData`, or data previously retrieved + * via {@link getQueryData}, in place. + * @param client - The client that owns this operation. + * @param queryKey - The query key to set data for. + * @param updater - Either the new data, or a function that receives the current data (which + * may be `undefined`) and returns the new data. + * @param options - Set `updatedAt` to override the timestamp the written data is recorded with. + * @returns The data that was written, or `undefined` if the updater returned `undefined` — in that case + * the write is skipped and the cache is left unchanged. + * @example + * ```ts + * setQueryData(queryClient, ['posts'], newPosts) + * + * // Or, using an updater function that receives the current data: + * setQueryData(queryClient, ['posts'], (oldPosts) => [...oldPosts, newPost]) + * ``` + */ +export function setQueryData< + TQueryFnData = unknown, + TTaggedQueryKey extends QueryKey = QueryKey, + TInferredQueryFnData = InferDataFromTag, +>( + client: QueryClient, + queryKey: TTaggedQueryKey, + updater: Updater< + InferDataFromTag, TTaggedQueryKey> | undefined, + NoInfer | undefined + >, + options?: SetDataOptions, +): NoInfer | undefined { + const defaultedOptions = defaultQueryOptions< + any, + any, + unknown, + any, + QueryKey + >(client, { queryKey }) + + const query = client[clientState].queryCache.get< + InferDataFromTag, TTaggedQueryKey> + >(defaultedOptions.queryHash) + const prevData = query?.state.data + const data = functionalUpdate(updater, prevData) + + if (data === undefined) { + return undefined + } + + return client[clientState].queryCache + .build(client, defaultedOptions) + .setData(data, { ...options, manual: true }) +} + +/** + * Imperative (non-reactive) way to retrieve an existing query's state. If the query does not + * exist, `undefined` is returned. + * @param client - The client that owns this operation. + * @param queryKey - The query key of the query to read. + * @returns The query's state, or `undefined` if no query with this key exists. + * @example + * ```ts + * const state = getQueryState(queryClient, ['posts']) + * console.log(state?.dataUpdatedAt) + * ``` + */ +export function getQueryState< + TQueryFnData = unknown, + TError = DefaultError, + TTaggedQueryKey extends QueryKey = QueryKey, + TInferredQueryFnData = InferDataFromTag, + TInferredError = InferErrorFromTag, +>( + client: QueryClient, + queryKey: TTaggedQueryKey, +): QueryState | undefined { + const options = defaultQueryOptions(client, { queryKey }) + return client[clientState].queryCache.get< + TInferredQueryFnData, + TInferredError + >(options.queryHash)?.state +} + +/** + * Asynchronous method to fetch and cache a query, resolving with the data or throwing with + * the error. + * + * If the query already exists in the cache and its data is not stale (per the given + * `staleTime`), the cached data is returned without fetching. Otherwise, the query is fetched + * and the promise resolves once the fetch settles. If a `select` function is provided, it is + * applied to the data in both cases (cached or freshly fetched) before it is returned. + * + * Unlike a reactive observer, retries are disabled by default here (`retry: false`) unless + * explicitly configured, since there is no component to catch a thrown error and retry through + * re-render. + * + * The accepted options are `QueryObserverOptions` minus the fields that only make sense for a + * reactive observer — `enabled`, `refetchInterval`, `refetchIntervalInBackground`, + * `refetchOnWindowFocus`, `refetchOnReconnect`, `refetchOnMount`, `retryOnMount`, + * `notifyOnChangeProps`, `throwOnError`, `suspense`, and `placeholderData` are not part of this + * method's options. + * Shared query options can contain `skipToken` as their `queryFn`. If the supplied options contain + * the token, the call skips fetching and resolves with existing data regardless of freshness. + * It applies `select` when data exists and resolves to `undefined` on a cache miss. + * Use {@link getQueryData} to read the cache directly. + * @param client - The client that owns this operation. + * @param options - The query options, including the `queryKey` and the `queryFn` used if the + * query needs to fetch. + * @returns A promise that resolves to the data, or to the result of `select` if provided. It + * rejects with the error from the fetch or from `select`. + * @example + * ```ts + * try { + * const data = await fetchQuery(queryClient, { queryKey, queryFn, staleTime: 10000 }) + * } catch (error) { + * console.log(error) + * } + * ``` + */ +export function fetchQuery< + TQueryFnData, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +>( + client: QueryClient, + options: WithoutSkipToken< + QueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + > + >, +): Promise + +export function fetchQuery< + TQueryFnData, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +>( + client: QueryClient, + options: QueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + >, +): Promise + +export async function fetchQuery< + TQueryFnData, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +>( + client: QueryClient, + options: QueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + >, +): Promise { + const defaultedOptions = defaultQueryOptions(client, options) + let queryData: TQueryData + + if (options.queryFn === skipToken) { + const cachedData = client[clientState].queryCache.get< + TQueryFnData, + TError, + TQueryData, + TQueryKey + >(defaultedOptions.queryHash)?.state.data + if (cachedData === undefined) return undefined + queryData = cachedData + } else { + // https://github.com/tannerlinsley/react-query/issues/652 + if (defaultedOptions.retry === undefined) { + defaultedOptions.retry = false + } + + const query = client[clientState].queryCache.build(client, defaultedOptions) + + const isStale = query.isStaleByTime( + resolveQueryValue(defaultedOptions.staleTime, query), + ) + + queryData = isStale + ? await query.fetch(defaultedOptions) + : (query.state.data as TQueryData) + } + + const select = defaultedOptions.select + + if (select) { + return select[1](queryData) + } + + return queryData as unknown as TData +} + +/** + * Resumes mutations that were paused because there was no network connection. Does nothing + * (resolving immediately) if the client is currently offline. + * @param client - The client that owns this operation. + * @returns A promise that resolves once the resumed mutations have settled. + * @example + * ```ts + * import { QueryClient, resumePausedMutations } from '@tanstack/react-query-pluggable' + * + * const queryClient = new QueryClient() + * await resumePausedMutations(queryClient) + * ``` + */ +export function resumePausedMutations(client: QueryClient): Promise { + if (onlineManager.isOnline()) { + return ( + client[mutationCacheKey]?.resumePausedMutations() ?? Promise.resolve([]) + ) + } + return Promise.resolve() +} + +/** + * Returns the query cache this client is connected to. + * @param client - The client that owns this operation. + * @returns The {@link QueryCache} instance. + * @example + * ```ts + * import { QueryClient, getQueryCache } from '@tanstack/react-query-pluggable' + * + * const queryClient = new QueryClient() + * const queryCache = getQueryCache(queryClient) + * const queries = queryCache.findAll({ queryKey: ['posts'] }) + * ``` + */ +export function getQueryCache(client: QueryClient): QueryCache { + return client[clientState].queryCache +} + +/** + * Returns the default options that were set when creating the client, or via + * {@link setDefaultOptions}. + * @param client - The client that owns this operation. + * @returns The client's current default options. + * @example + * ```ts + * import { QueryClient, getDefaultOptions } from '@tanstack/react-query-pluggable' + * + * const queryClient = new QueryClient() + * const defaultOptions = getDefaultOptions(queryClient) + * ``` + */ +export function getDefaultOptions(client: QueryClient): DefaultOptions { + return client[clientState].defaultOptions +} + +/** + * Dynamically sets the default options for this client, overwriting any previously defined + * default options. + * @param client - The client that owns this operation. + * @param options - The new default options for queries and mutations. + * @see {@link getDefaultOptions} + * @example + * ```ts + * import { QueryClient, setDefaultOptions } from '@tanstack/react-query-pluggable' + * + * const queryClient = new QueryClient() + * setDefaultOptions(queryClient, { + * queries: { + * staleTime: Infinity, + * }, + * }) + * ``` + */ +export function setDefaultOptions( + client: QueryClient, + options: DefaultOptions, +): void { + client[clientState].defaultOptions = options +} + +/** + * Sets default options for queries whose query key partially matches the given `queryKey`. + * + * If several registered query defaults match a given query key, they are merged together in + * registration order by {@link getQueryDefaults}, so register defaults from the + * most generic key to the least generic one — more specific defaults should be registered + * after more generic ones so they take precedence. + * @param client - The client that owns this operation. + * @param queryKey - The query key that query keys are partially matched against. + * @param options - The default options applied to matching queries. + * @example + * ```ts + * setQueryDefaults(queryClient, ['posts'], { queryFn: fetchPosts }) + * + * await fetchQuery(queryClient, { queryKey: ['posts'] }) + * ``` + */ +export function setQueryDefaults< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, +>( + client: QueryClient, + queryKey: QueryKey, + options: Partial< + OmitKeyof< + QueryObserverOptionsBase, + 'queryKey' + > + >, +): void { + ;(client[clientState].queryDefaults ??= new KeyDefaults()).set( + queryKey, + options, + client[clientState].queryCache.config.queryKey, + ) +} + +/** + * Returns the default options registered for queries whose query key partially matches the + * given `queryKey`, via {@link setQueryDefaults}. If multiple registered defaults + * match, they are merged together in registration order. + * @param client - The client that owns this operation. + * @param queryKey - The query key to look up registered defaults for. + * @returns The merged default options of every registration that matches, or an empty object if + * none match. + * @example + * ```ts + * const defaultOptions = getQueryDefaults(queryClient, ['posts']) + * ``` + */ +export function getQueryDefaults( + client: QueryClient, + queryKey: QueryKey, +): OmitKeyof, 'queryKey'> { + return ( + client[clientState].queryDefaults?.get( + queryKey, + client[clientState].queryCache.config.queryKey, + ) ?? {} + ) +} + +/** + * Sets default options for mutations whose mutation key partially matches the given + * `mutationKey`. As with {@link setQueryDefaults}, the order of registration + * matters when several registered defaults match the same mutation key. + * @param client - The client that owns this operation. + * @param mutationKey - The mutation key that mutation keys are partially matched against. + * @param options - The default options applied to matching mutations. + * @see {@link getMutationDefaults} + * @example + * ```ts + * setMutationDefaults(queryClient, ['addPost'], { mutationFn: addPost }) + * ``` + */ +export function setMutationDefaults< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +>( + client: QueryClient, + mutationKey: MutationKey, + options: OmitKeyof< + MutationObserverOptions, + 'mutationKey' + >, +): void { + ;(client[clientState].mutationDefaults ??= new KeyDefaults()).set( + mutationKey, + options, + client[mutationCacheKey]?.config.mutationKey, + ) +} + +/** + * Returns the default options registered for mutations whose mutation key partially matches + * the given `mutationKey`, via {@link setMutationDefaults}. If multiple registered + * defaults match, they are merged together in registration order. + * @param client - The client that owns this operation. + * @param mutationKey - The mutation key to look up registered defaults for. + * @returns The merged default options of every registration that matches, or an empty object if + * none match. + * @example + * ```ts + * const defaultOptions = getMutationDefaults(queryClient, ['addPost']) + * ``` + */ +export function getMutationDefaults( + client: QueryClient, + mutationKey: MutationKey, +): OmitKeyof, 'mutationKey'> { + return ( + client[clientState].mutationDefaults?.get( + mutationKey, + client[mutationCacheKey]?.config.mutationKey, + ) ?? {} + ) +} + +/** + * Called by framework adapters (e.g. inside `useQuery`) to resolve the options passed by the + * caller into their final, defaulted form: merging the client's own `defaultOptions.queries`, + * then `setQueryDefaults` for the given `queryKey`, then the caller's options on + * top. A no-op if the options are already defaulted (`_defaulted: true`). + * @param client - The client that owns this operation. + * @param options - The query options passed by the caller. + * @returns The defaulted options, with `queryHash` and dependent defaults (e.g. + * `refetchOnReconnect`) filled in. + */ +export function defaultQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +>( + client: QueryClient, + options: QueryObserverOptionsBase< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + >, +): DefaultedQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam +> { + if (options._defaulted) { + return options as DefaultedQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + > + } + + const queryDefaults = getQueryDefaults(client, options.queryKey) + const defaultedOptions = { + ...client[clientState].defaultOptions.queries, + ...queryDefaults, + ...options, + _defaulted: true, + } + + if (defaultedOptions.queryFn === defaultQueryFn) { + defaultedOptions.queryFn = + 'queryFn' in queryDefaults + ? queryDefaults.queryFn + : client[clientState].defaultOptions.queries?.queryFn + } + + if (!defaultedOptions.queryHash) { + defaultedOptions.queryHash = hashKeyByOptions( + defaultedOptions.queryKey, + client[clientState].queryCache.config.queryKey, + ) + } + + // dependent default values + if (defaultedOptions.refetchOnReconnect === undefined) { + defaultedOptions.refetchOnReconnect = + defaultedOptions.networkMode !== 'always' + } + if (defaultedOptions.throwOnError === undefined) { + defaultedOptions.throwOnError = !!defaultedOptions.suspense + } + + if (!defaultedOptions.networkMode && defaultedOptions.persister) { + defaultedOptions.networkMode = 'offlineFirst' + } + + if (defaultedOptions.queryFn === skipToken) { + defaultedOptions.enabled = false + } + + return defaultedOptions as DefaultedQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + > +} + +/** + * The mutation counterpart of {@link defaultQueryOptions}. Called by framework + * adapters (e.g. inside `useMutation`) to merge the client's `defaultOptions.mutations`, then + * `setMutationDefaults` for the given `mutationKey`, then the caller's options on + * top. A no-op if the options are already defaulted (`_defaulted: true`). + * @param client - The client that owns this operation. + * @param options - The mutation options passed by the caller. + * @returns The defaulted options. + */ +export function defaultMutationOptions< + T extends MutationOptions, +>(client: QueryClient, options?: T): T { + if (options?._defaulted) { + return options + } + return { + ...client[clientState].defaultOptions.mutations, + ...(options?.mutationKey && + getMutationDefaults(client, options.mutationKey)), + ...options, + _defaulted: true, + } as T +} + +/** + * Clears both the query cache and the mutation cache this client is connected to. + * This clears their garbage collection timers and cancels in-flight query fetches. + * Running mutations continue to execute. + * @param client - The client that owns this operation. + * @example + * ```ts + * import { QueryClient, clearQueryClient } from '@tanstack/react-query-pluggable' + * + * const queryClient = new QueryClient() + * clearQueryClient(queryClient) + * ``` + */ +export function clearQueryClient(client: QueryClient): void { + client[clientState].queryCache.clear() + client[mutationCacheKey]?.clear() +} diff --git a/packages/react-query-pluggable/src/runtime/queryObserver.ts b/packages/react-query-pluggable/src/runtime/queryObserver.ts new file mode 100644 index 00000000000..a87495bd53d --- /dev/null +++ b/packages/react-query-pluggable/src/runtime/queryObserver.ts @@ -0,0 +1,950 @@ +import { + Subscribable, + fetchState, + isServer as isServerEnvironment, + isValidTimeout, + noop, + shallowEqualObjects, + timeUntilStale, + timeoutManager, +} from '@tanstack/query-core/primitives' +import { notifyManager } from './notifyManager' +import { defaultQueryOptions, getQueryCache } from './queryClient' +import { resolveQueryValue } from './utils' +import type { QueryObserverResultReader } from '@tanstack/query-core' +import type { + FetchOptions, + ManagedTimerId, +} from '@tanstack/query-core/primitives' +import type { projectResult } from './projectResult' +import type { Query, QueryState } from './query' +import type { QueryClient } from './queryClient' +import type { PollingTimer } from './refetchInterval' +import type { + DefaultError, + DefaultedQueryObserverOptions, + PlaceholderValue, + QueryKey, + QueryObserverBaseResult, + QueryObserverOptions, + QueryObserverOptionsBase, + QueryObserverResult, + QueryOptions, + RefetchOptions, +} from './types' + +/** The last selector or placeholder error and when it occurred. */ +export type ProjectionFailure = { + /** The error thrown while computing the result. */ + error: TError + /** Timestamp of the failed computation. */ + errorUpdatedAt: number +} + +interface ObserverFetchOptions extends FetchOptions { + throwOnError?: boolean +} + +type QueryObserverListener = ( + result: QueryObserverResult, +) => void + +/** + * Selection and placeholder computation state shared by reads of the same result. + * @internal + */ +export interface QueryObserverResultContext< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey extends QueryKey, +> { + /** The optional result projection that produced this reader’s cached state. */ + project?: typeof projectResult + + /** The memo key and failure of the most recent selection. */ + selection?: { + key: { + input: TQueryData + select: (data: TQueryData) => TData + structuralSharing: QueryOptions< + TQueryFnData, + TError, + TQueryData, + TQueryKey + >['structuralSharing'] + } + failure?: ProjectionFailure + } + /** The last successful selection, used if selection fails. */ + selected?: { + data: TData + query?: Query + } + /** The unselected placeholder or factory error. */ + placeholder?: { + key: { + placeholderData: + | PlaceholderValue + | undefined + structuralSharing: QueryOptions< + TQueryFnData, + TError, + TQueryData, + TQueryKey + >['structuralSharing'] + previousQuery: + | Query + | undefined + previousState: QueryState | undefined + previousOptions: + | QueryOptions + | undefined + } + sourceQuery?: Query + input: TQueryData | undefined + failure?: ProjectionFailure + } +} + +/** + * Options supplied to an observer by a caller or already resolved by the client. + * @internal + */ +export type ObserverOptionsInput< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = + | QueryObserverOptions + | DefaultedQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + > + +/** + * A `QueryObserver` watches a single query in the `QueryCache` and computes a + * `QueryObserverResult` from its state, recomputing and notifying subscribers + * whenever the underlying query (or the observer's options) changes. It is + * the primitive that framework adapters (e.g. `useQuery`) build their hooks + * on top of, but it can also be used directly to observe and switch between + * queries outside of any framework. + * @example + * ```ts + * const observer = new QueryObserver(queryClient, { + * queryKey: ['posts'], + * queryFn: fetchPosts, + * }) + * + * const unsubscribe = observer.subscribe((result) => { + * console.log(result.data) + * }) + * ``` + */ +export class QueryObserver< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> extends Subscribable> { + #client: QueryClient + #currentQuery: Query = undefined! + #currentQueryInitialState: QueryState = undefined! + #currentResult: QueryObserverResult = undefined! + #resultContext: QueryObserverResultContext< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + > = {} + // This property keeps track of the last query with defined data. + // It will be used to pass the previous data and query to the placeholder function between renders. + #lastQueryWithDefinedData?: Query + #staleTimeoutId?: ManagedTimerId + #polling?: PollingTimer + #trackedProps = new Set() + + constructor( + client: QueryClient, + public options: ObserverOptionsInput< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + ) { + super() + + this.#client = client + + this.bindMethods() + this.setOptions(options) + } + + /** + * Binds the methods of the result (`refetch`) to the observer, so they keep working when destructured + * from it. Subclasses override it to bind their own result methods as well. + */ + protected bindMethods(): void { + this.refetch = this.refetch.bind(this) + } + + protected override onSubscribe(): void { + if (this.listeners.size === 1) { + this.#currentQuery.addObserver(this) + + if (shouldFetchOnMount(this.#currentQuery, this.options)) { + this.#executeFetch() + } else { + this.updateResult() + } + + this.#updateTimers() + } + } + + protected override onUnsubscribe(): void { + if (!this.hasListeners()) { + this.destroy() + } + } + + /** + * Returns whether the observed query is currently stale and configured + * (via the `refetchOnReconnect` option) to refetch when the network + * reconnects. + * @returns `true` if the observer should refetch the query on reconnect. + */ + shouldFetchOnReconnect(): boolean { + return shouldFetchOn( + this.#currentQuery, + this.options, + this.options.refetchOnReconnect, + ) + } + + /** + * Returns whether the observed query is currently stale and configured + * (via the `refetchOnWindowFocus` option) to refetch when the window + * regains focus. + * @returns `true` if the observer should refetch the query on window focus. + */ + shouldFetchOnWindowFocus(): boolean { + return shouldFetchOn( + this.#currentQuery, + this.options, + this.options.refetchOnWindowFocus, + ) + } + + /** + * Stops observing the current query: clears all listeners, cancels the + * stale and refetch-interval timers, and removes this observer from the + * query it was observing. + */ + destroy(): void { + this.listeners = new Set() + this.#clearStaleTimeout() + this.#polling?.stop() + this.#polling = undefined + this.#currentQuery.removeObserver(this) + } + + /** + * Updates the observer's options. This will re-resolve the query being + * observed (switching to a different query if the `queryKey` changed), + * trigger a fetch if the new options require one and the observer has + * subscribers, recompute the current result, and reschedule the stale and + * refetch-interval timers as needed. + * @param options - The new observer options. They are defaulted with {@link + * defaultQueryOptions} before being applied. + * @throws {Error} If `enabled` is neither a boolean nor a function. + * @example + * ```ts + * observer.setOptions({ queryKey: ['posts', 1], queryFn: () => fetchPost(1) }) + * // later: switch to a different query, reusing the same observer + * observer.setOptions({ queryKey: ['posts', 2], queryFn: () => fetchPost(2) }) + * ``` + */ + setOptions( + options: ObserverOptionsInput< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + ): void { + const prevOptions = this.options + const prevQuery = this.#currentQuery + + this.options = defaultQueryOptions(this.#client, options) + + if ( + this.options.enabled !== undefined && + typeof this.options.enabled !== 'boolean' && + typeof this.options.enabled !== 'function' && + typeof resolveQueryValue(this.options.enabled, this.#currentQuery) !== + 'boolean' + ) { + throw new Error( + 'Expected enabled to be a boolean or a callback that returns a boolean', + ) + } + + this.#updateQuery() + this.#currentQuery.setOptions(this.options) + + if ( + prevOptions._defaulted && + !shallowEqualObjects(this.options, prevOptions) + ) { + getQueryCache(this.#client).notify({ + type: 'observerOptionsUpdated', + query: this.#currentQuery, + observer: this, + }) + } + + const mounted = this.hasListeners() + + // Fetch if there are subscribers + if ( + mounted && + shouldFetchOptionally( + this.#currentQuery, + prevQuery, + this.options, + prevOptions, + ) + ) { + this.#executeFetch() + } + + // Update result + this.updateResult() + + // Update stale interval if needed + if ( + mounted && + (this.#currentQuery !== prevQuery || + resolveQueryValue(this.options.enabled, this.#currentQuery) !== + resolveQueryValue(prevOptions.enabled, this.#currentQuery) || + resolveQueryValue(this.options.staleTime, this.#currentQuery) !== + resolveQueryValue(prevOptions.staleTime, this.#currentQuery)) + ) { + this.#updateStaleTimeout() + } + + this.#updatePolling() + } + + /** + * Creates a result reader that captures the supplied query options. + * Reads cache the complete result locally and retain its reference while its + * fields are unchanged. They do not update this observer's committed result, + * options, or selection state. Missing queries are built in the query cache. + * Call `commit` after the render commits to apply the options and reuse the + * reader's computation. An abandoned reader needs no cleanup. + * @param options - The defaulted options used to read and commit the query result. + * @returns A reader with local snapshot and computation caches. + */ + createResultReader( + options: DefaultedQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + ): QueryObserverResultReader> { + const readerOptions = { ...options } + const context = { ...this.#resultContext } + let result = this.#currentResult + + const getSnapshot = () => { + const query = getQueryCache(this.#client).build( + this.#client, + readerOptions, + ) + readerOptions.select?.[0].reuse( + readerOptions, + query, + this.#resultContext, + context, + ) + + const nextResult = this.createResult( + query, + readerOptions, + context, + result, + ) + if (!shallowEqualObjects(nextResult, result)) { + result = nextResult + } + return result + } + + return { + getSnapshot, + commit: () => { + // Reuse selections computed since the last read. + getSnapshot() + this.#resultContext = { ...context } + this.setOptions(readerOptions) + }, + } + } + + /** + * Returns the most recently computed `QueryObserverResult` for the + * observed query. This is a point-in-time read; to be notified of updates + * as they happen, subscribe to the observer instead (its inherited + * `subscribe` method). + * @returns The observer's latest result. + * @example + * ```ts + * const result = observer.getCurrentResult() + * console.log(result.status, result.data) + * ``` + */ + getCurrentResult(): QueryObserverResult { + return this.#currentResult + } + + /** + * Wraps a `QueryObserverResult` in a `Proxy` that records which properties are read, via + * {@link QueryObserver#trackProp} (and an optional `onPropTracked` callback). Used by framework + * adapters when `notifyOnChangeProps` is not set, to implement its default "only re-render on + * properties you actually read" behavior. + * @param result - The result to wrap. + * @param onPropTracked - Called with the name of each property that is read. + * @returns A proxy of `result` that tracks property reads. + */ + trackResult( + result: QueryObserverResult, + onPropTracked?: (key: keyof QueryObserverResult) => void, + ): QueryObserverResult { + return new Proxy(result, { + get: (target, key) => { + this.trackProp(key as keyof QueryObserverResult) + onPropTracked?.(key as keyof QueryObserverResult) + return Reflect.get(target, key) + }, + }) + } + + /** + * Records that the given `QueryObserverResult` property was read, so a subsequent update only + * notifies this observer if a tracked property actually changed. {@link QueryObserver#trackResult} + * calls this on property access. `useQueries` tracks the same property across its observers + * when computing a combined result. + * @param key - The name of the property that was read. + */ + trackProp(key: keyof QueryObserverResult) { + this.#trackedProps.add(key) + } + + /** + * Returns the `Query` instance this observer is currently observing. + * @returns The observed query. + */ + getCurrentQuery(): Query { + return this.#currentQuery + } + + /** + * Refetches the observed query and returns a promise that resolves with + * the resulting `QueryObserverResult`. + * @param options - Set `cancelRefetch` to `false` to keep a running fetch instead of cancelling + * it, and `throwOnError` to `true` to reject when the refetch fails. + * @returns A promise that resolves with the result after the refetch. + * @example + * ```ts + * const result = await observer.refetch({ cancelRefetch: false }) + * console.log(result.data) + * ``` + */ + refetch( + options: RefetchOptions = {}, + ): Promise> { + return this.fetch(options) + } + + /** + * Fetches a query defined by the given options without affecting this + * observer's own tracked query or result, and returns a promise that + * resolves with the `QueryObserverResult` for that fetch. This is useful + * for prefetching data that another observer (e.g. a query about to be + * navigated to) will need, ahead of time. + * @param options - The observer options of the query to fetch. + * @returns A promise that resolves with the result for the fetched query. + * @example + * ```ts + * const result = await observer.fetchOptimistic({ + * queryKey: ['posts', 2], + * queryFn: () => fetchPost(2), + * }) + * console.log(result.data) + * ``` + */ + fetchOptimistic( + options: ObserverOptionsInput< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + ): Promise> { + const defaultedOptions = defaultQueryOptions(this.#client, options) + + const query = getQueryCache(this.#client).build( + this.#client, + defaultedOptions, + ) + + const cached = Promise.withResolvers>() + const unsubscribe = getQueryCache(this.#client).subscribe((event) => { + if ( + event.type === 'updated' && + event.query.queryHash === query.queryHash && + query.state.data !== undefined + ) { + unsubscribe() + cached.resolve(this.createResult(query, defaultedOptions)) + } + }) + + return Promise.race([ + query + .fetch(defaultedOptions) + .then(() => { + const result = this.createResult(query, defaultedOptions) + // Resolve the cache wait when the fetch succeeds. + cached.resolve(result) + return result + }) + .finally(unsubscribe), + cached.promise, + ]) + } + + /** + * Fetches the observed query and updates the result once the fetch settles. Used by `refetch` and, + * in `InfiniteQueryObserver`, to fetch more pages. + * @param fetchOptions - Options for this fetch. `cancelRefetch` defaults to `true`. + * @returns A promise that resolves with the updated result. + */ + protected fetch( + fetchOptions: ObserverFetchOptions, + ): Promise> { + return this.#executeFetch({ + ...fetchOptions, + cancelRefetch: fetchOptions.cancelRefetch ?? true, + }).then(() => { + this.updateResult() + return this.#currentResult + }) + } + + #executeFetch( + fetchOptions?: Omit, + ): Promise { + // Make sure we reference the latest query as the current one might have been removed + this.#updateQuery() + + // Fetch + let promise: Promise = this.#currentQuery.fetch( + this.options, + fetchOptions, + ) + + if (!fetchOptions?.throwOnError) { + promise = promise.catch(noop) + } + + return promise + } + + #shouldScheduleTimer(timeout: unknown): timeout is number { + return ( + !isServerEnvironment() && + resolveQueryValue(this.options.enabled, this.#currentQuery) !== false && + isValidTimeout(timeout) + ) + } + + #updateStaleTimeout(): void { + this.#clearStaleTimeout() + const staleTime = resolveQueryValue( + this.options.staleTime, + this.#currentQuery, + ) + + if (this.#currentResult.isStale || !this.#shouldScheduleTimer(staleTime)) { + return + } + + const time = timeUntilStale(this.#currentResult.dataUpdatedAt, staleTime) + + // The timeout is sometimes triggered 1 ms before the stale time expiration. + // To mitigate this issue we always add 1 ms to the timeout. + const timeout = time + 1 + + this.#staleTimeoutId = timeoutManager.setTimeout(() => { + if (!this.#currentResult.isStale) { + this.updateResult() + } + }, timeout) + } + + #updatePolling(restart = false): void { + const polling = resolveQueryValue( + this.options.refetchInterval, + this.#currentQuery, + ) + if (polling) { + this.#polling = polling.update(this, this.#polling, restart, () => + this.#executeFetch(), + ) + } else { + this.#polling?.stop() + this.#polling = undefined + } + } + + #updateTimers(): void { + this.#updateStaleTimeout() + this.#updatePolling(true) + } + + #clearStaleTimeout(): void { + if (this.#staleTimeoutId !== undefined) { + timeoutManager.clearTimeout(this.#staleTimeoutId) + this.#staleTimeoutId = undefined + } + } + + /** + * Computes the result for a query and options from the query's state, applying `select`, + * `placeholderData`, and the derived flags. Subclasses override it to add their own fields. + * @param query - The query to compute the result for. + * @param options - The observer options to compute the result with. + * @param context - The selection and placeholder state reused between computations. + * @param prevResult - The previous result used for structural sharing. + * @returns The computed result. + */ + protected createResult( + query: Query, + options: QueryObserverOptionsBase< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + context = this.#resultContext, + prevResult = this.#currentResult as + | QueryObserverResult + | undefined, + ): QueryObserverResult { + const prevQuery = this.#currentQuery + const prevOptions = this.options + const queryChange = query !== prevQuery + const queryInitialState = queryChange + ? query.state + : this.#currentQueryInitialState + + const { state } = query + const fetchOptimistically = + options._optimisticResults && + (this.hasListeners() + ? shouldFetchOptionally(query, prevQuery, options, prevOptions) + : shouldFetchOnMount(query, options)) + const newState = fetchOptimistically + ? { ...state, ...fetchState(state.data, query.options) } + : state + const fetchStatus = + options._optimisticResults === 'isRestoring' + ? 'idle' + : newState.fetchStatus + const feature = options.select?.[0] ?? options.placeholderData?.[0] + const project = feature?.project ?? context.project + const projection = project?.( + query, + newState, + options, + context, + prevResult?.data, + this.#lastQueryWithDefinedData, + ) + const { error, errorUpdatedAt, status } = projection ?? newState + const data = projection + ? projection.data + : (newState.data as unknown as TData | undefined) + const isPlaceholderData = projection?.isPlaceholderData ?? false + const isFetching = fetchStatus === 'fetching' + const isPending = status === 'pending' + const isError = status === 'error' + + const isLoading = isPending && isFetching + const hasData = data !== undefined + + const result: QueryObserverBaseResult = { + status, + fetchStatus, + isPending, + isSuccess: status === 'success', + isError, + isLoading, + data, + dataUpdatedAt: newState.dataUpdatedAt, + error, + errorUpdatedAt, + failureCount: newState.fetchFailureCount, + failureReason: newState.fetchFailureReason, + errorUpdateCount: newState.errorUpdateCount, + isFetched: query.isFetched(), + isFetchedAfterMount: + newState.dataUpdateCount > queryInitialState.dataUpdateCount || + newState.errorUpdateCount > queryInitialState.errorUpdateCount, + isFetching, + isRefetching: isFetching && !isPending, + isLoadingError: isError && !hasData, + isPaused: fetchStatus === 'paused', + isPlaceholderData, + isRefetchError: isError && hasData, + isStale: isStale(query, options), + refetch: this.refetch, + isEnabled: resolveQueryValue(options.enabled, query) !== false, + } + + const nextResult = result as QueryObserverResult + + return nextResult + } + + /** + * Recomputes and stores the current result from the current query/options, notifying listeners + * if it changed. Framework adapters call this right after subscribing to make sure no query + * update was missed in the gap between creating the observer and subscribing to it. + */ + updateResult(): void { + const prevResult = this.#currentResult as + | QueryObserverResult + | undefined + + const nextResult = this.createResult(this.#currentQuery, this.options) + + if (this.#currentQuery.state.data !== undefined) { + this.#lastQueryWithDefinedData = this.#currentQuery + } + + // Only notify and update result if something has changed + if (shallowEqualObjects(nextResult, prevResult)) { + return + } + + this.#currentResult = nextResult + + const shouldNotifyListeners = (): boolean => { + if (!prevResult) { + return true + } + + const { notifyOnChangeProps } = this.options + + if ( + notifyOnChangeProps === 'all' || + (notifyOnChangeProps !== 'none' && !this.#trackedProps.size) + ) { + return true + } + + if ( + this.options.throwOnError && + this.#currentResult.error !== prevResult.error + ) { + return true + } + + if (notifyOnChangeProps === 'none') { + return false + } + + for (const key of this.#trackedProps) { + if (this.#currentResult[key] !== prevResult[key]) { + return true + } + } + return false + } + + const notifyListeners = shouldNotifyListeners() + + notifyManager.batch(() => { + // First, trigger the listeners + if (notifyListeners) { + this.listeners.forEach((listener) => { + listener(this.#currentResult) + }) + } + + // Then the cache listeners + getQueryCache(this.#client).notify({ + query: this.#currentQuery, + type: 'observerResultsUpdated', + }) + }) + } + + #updateQuery(): void { + const query = getQueryCache(this.#client).build(this.#client, this.options) + + if (query === this.#currentQuery) { + return + } + + const prevQuery = this.#currentQuery as + | Query + | undefined + this.#currentQuery = query + this.#currentQueryInitialState = query.state + + if (this.hasListeners()) { + prevQuery?.removeObserver(this) + query.addObserver(this) + } + } + + /** + * Updates the observer's result when the observed query changes, and reschedules its timers if it + * has listeners. + * @internal + */ + onQueryUpdate(): void { + this.updateResult() + + if (this.hasListeners()) { + this.#updateTimers() + } + } +} + +/** + * Checks whether a query has no data yet and should do its initial load when an observer mounts. + * @param query - The query to check. + * @param options - The observer options. + * @returns `true` if the query is enabled, has no data, and isn't in an error state with + * `retryOnMount: false`. + */ +function shouldLoadOnMount( + query: Query, + options: QueryObserverOptionsBase, +): boolean { + return ( + resolveQueryValue(options.enabled, query) !== false && + query.state.data === undefined && + !( + query.state.status === 'error' && + resolveQueryValue(options.retryOnMount, query) === false + ) + ) +} + +/** + * Checks whether a query should fetch when an observer mounts: either for its initial load, or + * because it has data and `refetchOnMount` asks for a refetch. + * @param query - The query to check. + * @param options - The observer options. + * @returns `true` if the query should fetch on mount. + */ +function shouldFetchOnMount( + query: Query, + options: QueryObserverOptionsBase, +): boolean { + return ( + shouldLoadOnMount(query, options) || + (query.state.data !== undefined && + shouldFetchOn(query, options, options.refetchOnMount)) + ) +} + +/** + * Checks whether a query should fetch for a `refetchOnMount`, `refetchOnWindowFocus`, or + * `refetchOnReconnect` option. + * @param query - The query to check. + * @param options - The observer options. + * @param field - The value of the option to check. + * @returns `true` if the query is enabled, not static, and the option is `'always'`, or is not + * `false` and the query is stale. + */ +function shouldFetchOn( + query: Query, + options: QueryObserverOptionsBase, + field: (typeof options)['refetchOnMount'] & + (typeof options)['refetchOnWindowFocus'] & + (typeof options)['refetchOnReconnect'], +) { + if ( + resolveQueryValue(options.enabled, query) !== false && + resolveQueryValue(options.staleTime, query) !== 'static' + ) { + const value = resolveQueryValue(field, query) + + return value === 'always' || (value !== false && isStale(query, options)) + } + return false +} + +/** + * Checks whether a query should fetch after the observer's options change. + * @param query - The query observed with the new options. + * @param prevQuery - The query observed with the previous options. + * @param options - The new observer options. + * @param prevOptions - The previous observer options. + * @returns `true` if the query changed or was disabled before, it isn't a suspense query in an + * error state, and it is stale. + */ +function shouldFetchOptionally( + query: Query, + prevQuery: Query, + options: QueryObserverOptionsBase, + prevOptions: QueryObserverOptionsBase, +): boolean { + return ( + (query !== prevQuery || + resolveQueryValue(prevOptions.enabled, query) === false) && + (!options.suspense || query.state.status !== 'error') && + isStale(query, options) + ) +} + +/** + * Checks whether a query is stale for the given observer options. + * @param query - The query to check. + * @param options - The observer options, whose `enabled` and `staleTime` are used. + * @returns `true` if the query is enabled and its data is stale for `staleTime`. + */ +function isStale( + query: Query, + options: QueryObserverOptionsBase, +): boolean { + return ( + resolveQueryValue(options.enabled, query) !== false && + query.isStaleByTime(resolveQueryValue(options.staleTime, query)) + ) +} + +export type { QueryObserverResultReader } from '@tanstack/query-core' diff --git a/packages/react-query-pluggable/src/runtime/refetchInterval.ts b/packages/react-query-pluggable/src/runtime/refetchInterval.ts new file mode 100644 index 00000000000..332d9978b9d --- /dev/null +++ b/packages/react-query-pluggable/src/runtime/refetchInterval.ts @@ -0,0 +1,99 @@ +import { + focusManager, + isServer, + isValidTimeout, + timeoutManager, +} from '@tanstack/query-core/primitives' +import { resolveQueryValue } from './utils' +import type { QueryKey } from '@tanstack/query-core' +import type { Query } from './query' + +interface PollingTimer { + query: object + delay: number + stop: () => void +} + +interface PollingObserver { + getCurrentQuery: () => TQuery + hasListeners: () => boolean + options: { + enabled?: boolean | ((query: TQuery) => boolean) + refetchIntervalInBackground?: boolean + } +} + +type Delay = number | false | undefined + +/** An observer option created by {@link refetchInterval}. */ +interface RefetchInterval { + value: Delay | ((query: TQuery) => Delay) + update: typeof updatePolling +} + +/** + * Polls an observed query after the specified delay in milliseconds. + * @param value - A delay or a callback that selects the delay for the current query. + * Returning zero, false or undefined stops the timer. + * @returns A polling option for a query hook or client defaults. + * @example + * ```ts + * useQuery({ queryKey: ['orders'], queryFn: fetchOrders, refetchInterval: refetchInterval(3000) }) + * ``` + */ +export function refetchInterval(value: Delay): RefetchInterval +export function refetchInterval( + value: Delay | ((query: TQuery) => Delay), +): RefetchInterval +/* #__NO_SIDE_EFFECTS__ */ +export function refetchInterval( + value: Delay | ((query: TQuery) => Delay), +): RefetchInterval { + return { value, update: updatePolling } +} + +/** + * Reconciles one observer's timer with its current options and cached query. + * @param observer - Observer receiving the optional schedule. + * @param current - Timer installed during the preceding update. + * @param restart - Restarts the countdown after a query update or subscription. + * @param fetch - Refetches the observer's current query. + * @returns The active timer and its cleanup, when polling is enabled. + */ +function updatePolling( + this: RefetchInterval>, + observer: PollingObserver>, + current: PollingTimer | undefined, + restart: boolean, + fetch: () => void, +): PollingTimer | undefined { + const query = observer.getCurrentQuery() + const delay = resolveQueryValue(this.value, query) + if (!observer.hasListeners()) return + + if ( + isServer() || + !isValidTimeout(delay) || + delay === 0 || + resolveQueryValue(observer.options.enabled, query) === false + ) { + current?.stop() + return + } + if (!restart && current?.query === query && current.delay === delay) { + return current + } + current?.stop() + const id = timeoutManager.setInterval(() => { + if ( + observer.options.refetchIntervalInBackground || + focusManager.isFocused() + ) { + fetch() + } + }, delay) + + return { query, delay, stop: () => timeoutManager.clearInterval(id) } +} + +export type { PollingTimer, RefetchInterval } diff --git a/packages/react-query-pluggable/src/runtime/select.ts b/packages/react-query-pluggable/src/runtime/select.ts new file mode 100644 index 00000000000..c52e6bb2228 --- /dev/null +++ b/packages/react-query-pluggable/src/runtime/select.ts @@ -0,0 +1,134 @@ +import { + replaceData, + shallowEqualObjects, +} from '@tanstack/query-core/primitives' +import { projectResult } from './projectResult' +import type { Select } from './projectionTypes' +import type { Query } from './query' +import type { QueryObserverResultContext } from './queryObserver' +import type { QueryKey, QueryObserverOptionsBase } from './types' + +/* #__NO_SIDE_EFFECTS__ */ +/** + * Derives observer data from the cached query data. + * @param transform - Computes the selected data from the cached value. + * @returns A query selection option. + */ +export function select( + transform: (input: TInput) => TData, +): Select { + return [select, transform] +} + +select.project = projectResult +select.reuse = reuseSelection +select.resolve = resolveSelection + +/** + * Reuses the last committed selection when a reader sees the same input and selector. + * @param options - The reader's options. + * @param query - The query being read. + * @param committed - Memoized selections for the active observer. + * @param context - Selections local to this result reader. + */ +function reuseSelection< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey extends QueryKey, +>( + options: QueryObserverOptionsBase< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + query: Query, + committed: QueryObserverResultContext< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + context: QueryObserverResultContext< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, +): void { + const transform = options.select?.[1] + const input = query.state.data + if ( + input !== undefined && + transform && + shallowEqualObjects( + { + input, + select: transform, + structuralSharing: options.structuralSharing, + }, + committed.selection?.key, + ) + ) { + context.selection = committed.selection + context.selected = committed.selected + } +} + +/** + * Memoizes the result or error of applying a selector to query or placeholder data. + * @param options - Options controlling structural sharing. + * @param transform - The caller's selector. + * @param context - Selection state for this observer or render. + * @param previousData - The previous data for structural sharing. + * @param input - The value passed to the selector. + * @param sourceQuery - The query supplying the selected data, if any. + */ +function resolveSelection< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey extends QueryKey, +>( + options: QueryObserverOptionsBase< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + transform: (data: TQueryData) => TData, + context: QueryObserverResultContext< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + previousData: TData | undefined, + input: TQueryData, + sourceQuery: Query | undefined, +): void { + const key = { + input, + select: transform, + structuralSharing: options.structuralSharing, + } + if (shallowEqualObjects(key, context.selection?.key)) return + try { + const data = replaceData(previousData, transform(input), options) + context.selected = { data, query: sourceQuery } + context.selection = { key } + } catch (error) { + context.selection = { + key, + failure: { error: error as TError, errorUpdatedAt: Date.now() }, + } + } +} diff --git a/packages/react-query-pluggable/src/runtime/serialScope.ts b/packages/react-query-pluggable/src/runtime/serialScope.ts new file mode 100644 index 00000000000..96f042d860a --- /dev/null +++ b/packages/react-query-pluggable/src/runtime/serialScope.ts @@ -0,0 +1,96 @@ +import type { Mutation } from './mutation' +import type { MutationCache } from './mutationCache' + +type QueuedMutation = Mutation + +// Each cache owns its own queues, even when clients reuse the same option. +const queues = new WeakMap>>() + +/** Runs mutations with the same ID in registration order within one cache. */ +class SerialScope { + constructor(readonly id: string) {} + + /** + * Registers a mutation in this cache's queue. + * @internal + * @param cache - The cache owning this queue. + * @param mutation - The mutation to register. + */ + add(cache: MutationCache, mutation: QueuedMutation): void { + let scopes = queues.get(cache) + if (!scopes) { + scopes = new Map() + queues.set(cache, scopes) + } + let queue = scopes.get(this.id) + if (!queue) { + queue = new Set() + scopes.set(this.id, queue) + } + queue.add(mutation) + } + + /** + * Releases the mutation and any empty queue. + * @internal + * @param cache - The cache owning this queue. + * @param mutation - The mutation to remove. + */ + remove(cache: MutationCache, mutation: QueuedMutation): void { + const scopes = queues.get(cache) + if (!scopes) return + const queue = scopes.get(this.id) + if (queue?.delete(mutation) && !queue.size) { + scopes.delete(this.id) + if (!scopes.size) queues.delete(cache) + } + } + + /** + * Checks whether this mutation is the first pending member. + * @internal + * @param cache - The cache owning this queue. + * @param mutation - The mutation to check. + * @returns Whether this mutation can start or continue. + */ + canRun(cache: MutationCache, mutation: QueuedMutation): boolean { + const queue = queues.get(cache)?.get(this.id) + if (queue) { + for (const entry of queue) { + if (entry.state.status === 'pending') return entry === mutation + } + } + return true + } + + /** + * Resumes the first waiting mutation after its predecessor settles. + * @internal + * @param cache - The cache owning this queue. + * @param mutation - The mutation to finish. + * @returns The next waiting mutation’s promise, if present. + */ + runNext( + cache: MutationCache, + mutation: QueuedMutation, + ): Promise | undefined { + const queue = queues.get(cache)?.get(this.id) + if (queue) { + for (const entry of queue) { + if (entry !== mutation && entry.state.isPaused) return entry.continue() + } + } + return undefined + } +} + +/** + * Selects FIFO execution for mutations sharing this ID in the same cache. + * @param id - The queue identifier, preserved in dehydrated mutation snapshots. + * @returns The value to pass to the mutation's `scope` option. + */ +export function serialScope(id: string): SerialScope { + return new SerialScope(id) +} + +export type { SerialScope } diff --git a/packages/react-query-pluggable/src/runtime/streamedQuery.ts b/packages/react-query-pluggable/src/runtime/streamedQuery.ts new file mode 100644 index 00000000000..428da5442bb --- /dev/null +++ b/packages/react-query-pluggable/src/runtime/streamedQuery.ts @@ -0,0 +1,156 @@ +import { + addConsumeAwareSignal, + fetchSignal, +} from '@tanstack/query-core/primitives' +import { getQueryCache, getQueryData, setQueryData } from './queryClient' +import type { FetchSignalContext } from '@tanstack/query-core/primitives' +import type { + OmitKeyof, + QueryFunction, + QueryFunctionContext, + QueryKey, +} from './types' + +type StreamedQueryParams = + | SimpleStreamedQueryParams + | ReducibleStreamedQueryParams + +type SimpleStreamedQueryParams< + TQueryFnData, + TQueryKey extends QueryKey, +> = BaseStreamedQueryParams & { + reducer?: never + initialValue?: never +} + +type ReducibleStreamedQueryParams< + TQueryFnData, + TData, + TQueryKey extends QueryKey, +> = BaseStreamedQueryParams & { + /** + * Combines the accumulated data with the next chunk. Provide `initialValue` with a custom reducer. + */ + reducer: (acc: TData, chunk: TQueryFnData) => TData + /** + * The starting value for the reducer when there is no cached data or when + * `refetchMode` is `'replace'` during a refetch. + */ + initialValue: TData +} + +type BaseStreamedQueryParams = { + /** Returns an `AsyncIterable` or a promise that resolves to one. */ + streamFn: ( + context: QueryFunctionContext, + ) => AsyncIterable | Promise> + /** + * Defines how refetches are handled. + * - `'reset'` (default): resets the query to its initial state before reading the stream. + * - `'append'`: appends new data to the existing data. + * - `'replace'`: writes all data to the cache once the stream ends. + */ + refetchMode?: 'append' | 'reset' | 'replace' +} + +/** + * Creates a query function that streams data from an `AsyncIterable`. + * By default, the query collects chunks into an array in the order they arrive. + * If there is no cached data, the first chunk moves the query from `pending` to `success`. + * If the stream ends without producing any chunks, the query uses the cached data or + * the initial value. With a `'replace'` refetch, it uses the initial value. + * The query's `fetchStatus` stays `fetching` while the stream is active. + * Explicit cancellation stops further cache updates, even if `streamFn` does not read `signal`. + * If `streamFn` does not read `signal`, the stream continues after the last observer unsubscribes. + * @param options - The `streamFn` that returns an AsyncIterable to stream data from, and the optional + * `refetchMode`, `reducer`, and `initialValue` options. + * @returns A query function to pass as `queryFn`. + * @example + * ```ts + * await fetchQuery(queryClient, { + * queryKey: ['data'], + * queryFn: streamedQuery({ + * streamFn: fetchDataInChunks, + * }), + * }) + * ``` + */ +export function streamedQuery< + TQueryFnData = unknown, + TData = Array, + TQueryKey extends QueryKey = QueryKey, +>({ + streamFn, + refetchMode = 'reset', + reducer = (items, chunk) => + [...(items as Array), chunk] as TData, + initialValue = [] as TData, +}: StreamedQueryParams): QueryFunction< + TData, + TQueryKey +> { + return async (context) => { + const signalContext: FetchSignalContext = context + const signal = signalContext[fetchSignal] + if (signal?.aborted) { + return initialValue + } + + const query = getQueryCache(context.client).find({ + queryKey: context.queryKey, + exact: true, + }) + const isRefetch = !!query && query.isFetched() + if (isRefetch && refetchMode === 'reset') { + query.setState({ + ...query.resetState, + fetchStatus: 'fetching', + }) + } + + let result = initialValue + + let cancelled = false as boolean + const streamFnContext = addConsumeAwareSignal< + OmitKeyof + >( + { + client: context.client, + meta: context.meta, + queryKey: context.queryKey, + pageParam: context.pageParam, + }, + () => context.signal, + () => (cancelled = true), + signal, + ) + + const isStreamInactive = () => cancelled || signal?.aborted === true + const stream = await streamFn(streamFnContext) + + const isReplaceRefetch = isRefetch && refetchMode === 'replace' + + for await (const chunk of stream) { + if (isStreamInactive()) { + break + } + + if (isReplaceRefetch) { + // don't append to the cache directly when replace-refetching + result = reducer(result, chunk) + } else { + setQueryData(context.client, context.queryKey, (prev) => + reducer(prev === undefined ? initialValue : prev, chunk), + ) + } + } + + // finalize result: replace-refetching needs to write to the cache + if (isReplaceRefetch && !isStreamInactive()) { + setQueryData(context.client, context.queryKey, result) + } + + const data = getQueryData(context.client, context.queryKey) + return data === undefined ? initialValue : data + } +} diff --git a/packages/react-query-pluggable/src/runtime/types.ts b/packages/react-query-pluggable/src/runtime/types.ts new file mode 100644 index 00000000000..f1bc0a0e9b2 --- /dev/null +++ b/packages/react-query-pluggable/src/runtime/types.ts @@ -0,0 +1,788 @@ +import type { + DefaultError, + InfiniteData, + InfiniteQueryPageParamsOptions, + OmitKeyof, + QueryKey, + QueryMeta, + StaleTime, + WithRequired, +} from '@tanstack/query-core' +import type * as Core from '@tanstack/query-core' +import type { + DefaultQueryFn, + QueryTypeFilter, + SkipToken, +} from '@tanstack/query-core/primitives' +import type * as CorePrimitives from '@tanstack/query-core/primitives' +import type { DehydrateOptions, HydrateOptions } from './hydration' +import type { MutationCache } from './mutationCache' +import type { placeholderData } from './placeholderData' +import type { Select } from './projectionTypes' +import type { Query } from './query' +import type { QueryCache } from './queryCache' +import type { QueryClient } from './queryClient' +import type { RefetchInterval } from './refetchInterval' +import type { SerialScope } from './serialScope' +import type { QueryFilters } from './utils' + +/** @inline */ +export type QueryFunction< + T = unknown, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = (context: QueryFunctionContext) => T | Promise + +/** @inline */ +export type StaleTimeFunction< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = + | StaleTime + | ((query: Query) => StaleTime) + +/** @inline */ +export type QueryBooleanOption< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = + | boolean + | ((query: Query) => boolean) + +/** @inline */ +export type QueryPersister< + T = unknown, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = [TPageParam] extends [never] + ? ( + queryFn: QueryFunction, + context: QueryFunctionContext, + query: Query, + ) => T | Promise + : ( + queryFn: QueryFunction, + context: QueryFunctionContext, + query: Query, + ) => T | Promise + +/** + * The object passed to `queryFn`: the `QueryClient`, the `queryKey`, an `AbortSignal` that aborts + * when the query is cancelled, the query's `meta`, and for infinite queries the `pageParam` of the + * page being fetched. + */ +export type QueryFunctionContext< + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = [TPageParam] extends [never] + ? { + client: QueryClient + queryKey: TQueryKey + signal: AbortSignal + meta: QueryMeta | undefined + pageParam?: unknown + } + : { + client: QueryClient + queryKey: TQueryKey + signal: AbortSignal + meta: QueryMeta | undefined + pageParam: TPageParam + } + +/** @inline */ +export type PlaceholderDataFunction< + TQueryFnData = unknown, + TError = DefaultError, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = ( + previousData: TQueryData | undefined, + previousQuery: Query | undefined, +) => TQueryData | undefined + +/** Query cache options. The query function and persister receive this adapter’s client. */ +export interface QueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> extends Omit< + Core.QueryOptions, + 'queryFn' | 'persister' +> { + /** + * The function that the query will use to request data. + * Pass `defaultQueryFn` to use the function configured in the client's query defaults. + * Pass `skipToken` to disable a query without a function where supported. + * Receives a {@link QueryFunctionContext}. + * Must return a promise that will either resolve data or throw an error. The data cannot be `undefined`. + */ + queryFn?: + | QueryFunction + | SkipToken + | DefaultQueryFn + /** + * This option can be used to persist the result of a query to an external storage, bypassing the need to actually + * call the `queryFn`. Useful for persisting a query's data across e.g. server/client boundaries. + */ + persister?: QueryPersister, TPageParam> +} + +/** @inline */ +export type ThrowOnError< + TQueryFnData, + TError, + TQueryData, + TQueryKey extends QueryKey, +> = + | boolean + | (( + error: TError, + query: Query, + ) => boolean) + +/** Shared observer options, including opt-in selection, placeholder data, and polling. */ +export interface QueryObserverOptionsBase< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> + extends + WithRequired< + QueryOptions, + 'queryKey' + >, + Pick< + CorePrimitives.QueryObserverOptionsBase< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + >, + | 'refetchIntervalInBackground' + | 'notifyOnChangeProps' + | 'suspense' + | '_optimisticResults' + > { + /** + * Set this to `false` or a function that returns `false` to disable automatic refetching when the query mounts or changes query keys. + * To refetch the query, use the `refetch` method returned from the `useQuery` instance. + * Accepts a boolean or function that returns a boolean. + * @defaultValue true + */ + enabled?: QueryBooleanOption + /** + * The time in milliseconds after data is considered stale. + * If set to `Infinity`, the data will never be considered stale. + * If set to `'static'`, the data will never be considered stale. + * If set to a function, the function will be executed with the query to compute a `staleTime`. + * @defaultValue 0 + */ + staleTime?: StaleTimeFunction + /** Set refetchInterval(milliseconds) or return it from a callback to poll the query. */ + refetchInterval?: + | false + | RefetchInterval> + | (( + query: Query, + ) => + | false + | undefined + | RefetchInterval>) + /** + * If set to `true`, the query will refetch on window focus if the data is stale. + * If set to `false`, the query will not refetch on window focus. + * If set to `'always'`, the query will always refetch on window focus (except when `staleTime: 'static'` is used). + * If set to a function, the function will be executed with the latest data and query to compute the value. + * @defaultValue true + */ + refetchOnWindowFocus?: + | boolean + | 'always' + | (( + query: Query, + ) => boolean | 'always') + /** + * If set to `true`, the query will refetch on reconnect if the data is stale. + * If set to `false`, the query will not refetch on reconnect. + * If set to `'always'`, the query will always refetch on reconnect (except when `staleTime: 'static'` is used). + * If set to a function, the function will be executed with the latest data and query to compute the value. + * + * Defaults to `true` unless `networkMode` is `'always'`. + */ + refetchOnReconnect?: + | boolean + | 'always' + | (( + query: Query, + ) => boolean | 'always') + /** + * If set to `true`, the query will refetch on mount if the data is stale. + * If set to `false`, will disable additional instances of a query to trigger background refetch. + * If set to `'always'`, the query will always refetch on mount (except when `staleTime: 'static'` is used). + * If set to a function, the function will be executed with the latest data and query to compute the value + * @defaultValue true + */ + refetchOnMount?: + | boolean + | 'always' + | (( + query: Query, + ) => boolean | 'always') + /** + * If set to `false`, the query will not be retried on mount if it contains an error. + * If set to a function, the function will be executed with the query to compute the value. + * @defaultValue true + */ + retryOnMount?: QueryBooleanOption + /** + * Whether errors should be thrown instead of setting the `error` property. + * If set to `true` or `suspense` is `true`, all errors will be thrown to the error boundary. + * If set to `false` and `suspense` is `false`, errors are returned as state. + * If set to a function, it will be passed the error and the query, and it should return a boolean indicating whether to show the error in an error boundary (`true`) or return the error as state (`false`). + * @defaultValue false + */ + throwOnError?: ThrowOnError + /** Pass [select, transform] to derive the data returned by this observer. */ + select?: Select + /** Wrap a value or factory with placeholderData to display it while the query loads. */ + placeholderData?: readonly [ + feature: typeof placeholderData, + value: PlaceholderValue, + ] +} + +/** + * The options of a `QueryObserver`, and of the hooks built on it like `useQuery`: the + * {@link QueryOptions} of the query, plus options that control the observer, such as `enabled`, + * `staleTime`, `refetchInterval`, `select`, and `placeholderData`. + * Pass a `queryFn` or use `defaultQueryFn` to select the client defaults. + */ +export interface QueryObserverOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> extends WithRequired< + QueryObserverOptionsBase< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + >, + 'queryFn' +> {} + +/** + * The {@link QueryObserverOptions} after `defaultQueryOptions` has applied the + * defaults, so `throwOnError`, `refetchOnReconnect`, and `queryHash` are always set. + */ +export type DefaultedQueryObserverOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = WithRequired< + QueryObserverOptionsBase< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + >, + 'throwOnError' | 'refetchOnReconnect' | 'queryHash' +> + +/** + * The options of an `InfiniteQueryObserver`: {@link QueryObserverOptions} whose query data is + * {@link InfiniteData}, plus the page param options. + */ +export interface InfiniteQueryObserverOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> + extends + QueryObserverOptions< + TQueryFnData, + TError, + TData, + InfiniteData, + TQueryKey, + TPageParam + >, + InfiniteQueryPageParamsOptions {} + +/** + * The {@link InfiniteQueryObserverOptions} after `defaultQueryOptions` has applied the + * defaults, so `throwOnError`, `refetchOnReconnect`, and `queryHash` are always set. + */ +export type DefaultedInfiniteQueryObserverOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> = DefaultedQueryObserverOptions< + TQueryFnData, + TError, + TData, + InfiniteData, + TQueryKey, + TPageParam +> & + InfiniteQueryPageParamsOptions + +/** + * The options of `fetchQuery`: the {@link QueryOptions} of the query, plus a `staleTime` + * that decides whether cached data is returned instead of fetching, and a `select` that only + * transforms the value the call resolves with. + */ +export interface QueryExecuteOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> + extends + WithRequired< + QueryOptions, + 'queryKey' + >, + Pick< + Core.QueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + >, + 'initialPageParam' + > { + /** Pass [select, transform] to derive the resolved value while retaining the fetched data in the cache. */ + select?: Select + /** + * The time in milliseconds after data is considered stale. + * If the data is fresh it will be returned from the cache. + */ + staleTime?: StaleTimeFunction +} + +/** + * The options of `fetchInfiniteQuery`. Extends {@link QueryExecuteOptions} + * with `initialPageParam`, `getNextPageParam`, and the optional `pages` count. + */ +export type InfiniteQueryExecuteOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> = Omit< + QueryExecuteOptions< + TQueryFnData, + TError, + TData, + InfiniteData, + TQueryKey, + TPageParam + >, + 'initialPageParam' +> & + InfiniteQueryFetchPageOptions + +/** + * The filters of `invalidateQueries`: the {@link QueryFilters} that select the queries + * to invalidate, plus `refetchType` to choose which of them are refetched. + */ +export interface InvalidateQueryFilters< + TQueryKey extends QueryKey = QueryKey, +> extends QueryFilters { + /** + * Controls which of the matched (now-invalidated) queries are refetched in the background. + * + * - `'active'`: only queries with at least one active observer are refetched. + * - `'inactive'`: only queries with no active observer are refetched. + * - `'all'`: every matched query is refetched, active or not. + * - `'none'`: no query is refetched; matched queries are only marked as invalidated. + * @defaultValue 'active' + */ + refetchType?: QueryTypeFilter | 'none' +} + +/** + * The filters of `refetchQueries`, which select the queries to refetch. + */ +export interface RefetchQueryFilters< + TQueryKey extends QueryKey = QueryKey, +> extends QueryFilters {} + +/** + * The object passed to `mutationFn` and the mutation callbacks: the `QueryClient`, the mutation's + * `meta`, and its `mutationKey`. + */ +export type MutationFunctionContext = Core.Override< + Core.MutationFunctionContext, + { client: QueryClient } +> + +/** @inline */ +export type MutationFunction = ( + variables: TVariables, + context: MutationFunctionContext, +) => Promise + +/** + * The options of a mutation: its `mutationFn`, `mutationKey`, callbacks, retries, `scope`, and so + * on. + */ +export interface MutationOptions< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> extends Omit< + Core.MutationOptions, + 'mutationFn' | 'onMutate' | 'onSuccess' | 'onError' | 'onSettled' | 'scope' +> { + /** + * The function that performs the asynchronous task this mutation runs. + * Required, unless a default mutation function has been set for the matching `mutationKey` via + * `setMutationDefaults`. + * Receives the `variables` passed to `mutate`, and a {@link MutationFunctionContext} holding the + * `QueryClient`, the `mutationKey` and `meta`. + * Must return a promise that resolves the mutation's data. + */ + mutationFn?: MutationFunction + /** + * This function fires before the mutation function runs, and receives the same variables. + * Useful for optimistic updates applied in the hope that the mutation succeeds. + * The value it returns is passed to `onSuccess`, `onError` and `onSettled` as `onMutateResult`, + * which is where an optimistic update is usually rolled back. + * If a promise is returned, it is awaited before the mutation function runs. + */ + onMutate?: ( + variables: TVariables, + context: MutationFunctionContext, + ) => Promise | TOnMutateResult + /** + * This function fires when the mutation succeeds, and is passed the mutation's result. + * If a promise is returned, it is awaited before `onSettled` runs. + */ + onSuccess?: ( + data: TData, + variables: TVariables, + onMutateResult: TOnMutateResult, + context: MutationFunctionContext, + ) => Promise | unknown + /** + * This function fires when the mutation encounters an error, and is passed the error. + * If a promise is returned, it is awaited before `onSettled` runs. + */ + onError?: ( + error: TError, + variables: TVariables, + onMutateResult: TOnMutateResult | undefined, + context: MutationFunctionContext, + ) => Promise | unknown + /** + * This function fires when the mutation either succeeds or errors, and is passed either the data + * or the error. + * If a promise is returned, it is awaited before the mutation settles. + */ + onSettled?: ( + data: TData | undefined, + error: TError | null, + variables: TVariables, + onMutateResult: TOnMutateResult | undefined, + context: MutationFunctionContext, + ) => Promise | unknown + /** Pass serialScope(id) to run mutations with this ID in order. */ + scope?: SerialScope +} + +/** + * The options of a `MutationObserver`, and of the hooks built on it like `useMutation`: the + * {@link MutationOptions}, plus `throwOnError`. + */ +export interface MutationObserverOptions< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> + extends + MutationOptions, + Pick< + Core.MutationObserverOptions, + 'throwOnError' + > {} + +/** + * The callbacks that can be passed to `mutate` for a single call. They run after the callbacks of + * the mutation options. + */ +export interface MutateOptions< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> { + /** + * Called when the mutation of this call succeeds, after the `onSuccess` of the mutation options. + */ + onSuccess?: ( + data: TData, + variables: TVariables, + onMutateResult: TOnMutateResult | undefined, + context: MutationFunctionContext, + ) => void + /** + * Called when the mutation of this call fails, after the `onError` of the mutation options. + */ + onError?: ( + error: TError, + variables: TVariables, + onMutateResult: TOnMutateResult | undefined, + context: MutationFunctionContext, + ) => void + /** + * Called when the mutation of this call succeeds or fails, after the `onSettled` of the mutation + * options. + */ + onSettled?: ( + data: TData | undefined, + error: TError | null, + variables: TVariables, + onMutateResult: TOnMutateResult | undefined, + context: MutationFunctionContext, + ) => void +} + +/** + * The parameters of {@link MutateFunction}: `variables`, optional when `TVariables` accepts + * `undefined`, and the {@link MutateOptions} for that call. + */ +export type MutateFunctionRest< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = undefined extends TVariables + ? [ + variables?: TVariables, + options?: MutateOptions, + ] + : [ + variables: TVariables, + options?: MutateOptions, + ] + +/** + * The `mutate` function of a `MutationObserver`: runs the mutation with the given variables and + * resolves with its data. + */ +export type MutateFunction< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = ( + ...rest: MutateFunctionRest +) => Promise + +type WithMutationFunction = Core.Override< + TResult, + { mutate: TMutate } +> + +/** + * The properties shared by every state of a mutation result, like `data`, `error`, `variables`, + * `status`, the `is*` flags, `mutate`, and `reset`. + */ +export type MutationObserverBaseResult< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = WithMutationFunction< + Core.MutationObserverBaseResult, + MutateFunction +> + +/** + * The result of a `MutationObserver`, and of the hooks built on it like `useMutation`. Narrow it by + * `status` or the `is*` flags to get the type of each state. + */ +export type MutationObserverResult< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = WithMutationFunction< + Core.MutationObserverResult, + MutateFunction +> + +/** + * A mutation result in the `idle` state: the mutation hasn't run yet, or was reset. + */ +export type MutationObserverIdleResult< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = Extract< + MutationObserverResult, + { status: 'idle' } +> + +/** + * A mutation result in the `pending` state while the mutation runs. + */ +export type MutationObserverLoadingResult< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = Extract< + MutationObserverResult, + { status: 'pending' } +> + +/** + * A mutation result in the `error` state after the mutation failed. + */ +export type MutationObserverErrorResult< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = Extract< + MutationObserverResult, + { status: 'error' } +> + +/** + * A mutation result in the `success` state after the mutation succeeded. + */ +export type MutationObserverSuccessResult< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = Extract< + MutationObserverResult, + { status: 'success' } +> + +/** The caches and default options to use when creating a pluggable client. */ +export interface QueryClientConfig { + /** The query cache this client is connected to. A new `QueryCache` is created if not provided. */ + queryCache?: QueryCache + /** + * The mutation cache this client is connected to. A new `MutationCache` is created if not + * provided. + */ + mutationCache?: MutationCache + /** Default options for all queries and mutations created through this client. */ + defaultOptions?: DefaultOptions +} + +/** + * The default options of a `QueryClient`, applied to every query (`queries`), mutation + * (`mutations`), `hydrate`, and `dehydrate` call unless overridden. + */ +export interface DefaultOptions { + /** Default options applied to every query, unless overridden per-query. */ + queries?: OmitKeyof< + QueryObserverOptionsBase, + 'suspense' | 'queryKey' + > + /** Default options applied to every mutation, unless overridden per-mutation. */ + mutations?: MutationObserverOptions + /** Default options used when hydrating queries and mutations; see {@link HydrateOptions}. */ + hydrate?: HydrateOptions['defaultOptions'] + /** Default options used when dehydrating the client's caches; see {@link DehydrateOptions}. */ + dehydrate?: DehydrateOptions +} + +/** A raw placeholder value or the callback that supplies it for a query. */ +export type PlaceholderValue = + | NonFunctionGuard + | PlaceholderDataFunction< + NonFunctionGuard, + TError, + NonFunctionGuard, + TQueryKey + > + +type InfiniteQueryFetchPageOptions = Pick< + InfiniteQueryPageParamsOptions, + 'initialPageParam' | 'getNextPageParam' +> & { + /** + * The number of pages to fetch. Defaults to the number of cached pages, + * or one page if the cache has no pages. + */ + pages?: number +} + +// oxlint-disable-next-line typescript/no-unsafe-function-type -- excludes all callable and constructable values +type NonFunctionGuard = T extends Function ? never : T + +export { + dataTagSymbol, + dataTagErrorSymbol, + unsetMarker, +} from '@tanstack/query-core/primitives' + +export type { + OmitKeyof, + DefaultError, + QueryKey, + InferDataFromTag, + InferErrorFromTag, + StaleTime, + CacheKeyConfig, + InfiniteData, + QueryMeta, + InfiniteQueryPageParamsOptions, + WithRequired, + RefetchOptions, + InvalidateOptions, + ResetOptions, + FetchNextPageOptions, + FetchPreviousPageOptions, + QueryObserverBaseResult, + QueryObserverResult, + InfiniteQueryObserverBaseResult, + InfiniteQueryObserverResult, + MutationKey, + MutationMeta, + CancelOptions, + SetDataOptions, +} from '@tanstack/query-core' diff --git a/packages/react-query-pluggable/src/runtime/utils.ts b/packages/react-query-pluggable/src/runtime/utils.ts new file mode 100644 index 00000000000..64bf89b3993 --- /dev/null +++ b/packages/react-query-pluggable/src/runtime/utils.ts @@ -0,0 +1,300 @@ +import { + defaultQueryFn, + hashKeyByOptions, + partialMatchKey, + skipToken, +} from '@tanstack/query-core/primitives' +import { identity } from './identity' +import type * as Core from '@tanstack/query-core' +import type { DefaultQueryFn, SkipToken } from '@tanstack/query-core/primitives' +import type { Mutation } from './mutation' +import type { FetchOptions, Query } from './query' +import type { + CacheKeyConfig, + DefaultError, + MutationKey, + QueryFunction, + QueryKey, +} from './types' + +/** + * Filters used to select queries, for example in `getQueriesData` or `invalidateQueries`. + * All provided filters must match; filters that are left unspecified are ignored. + */ +export interface QueryFilters< + TQueryKey extends QueryKey = QueryKey, +> extends Omit, 'predicate'> { + /** + * Include queries matching this predicate function + */ + predicate?: (query: Query) => boolean +} + +/** + * Filters used to select mutations, for example in `mutationCache.findAll` or `isMutating`. + * All provided filters must match; filters that are left unspecified are ignored. + */ +export interface MutationFilters< + TData = unknown, + TError = DefaultError, + TVariables = unknown, + TOnMutateResult = unknown, +> extends Omit< + Core.MutationFilters, + 'predicate' +> { + /** + * Include mutations matching this predicate function + */ + predicate?: ( + mutation: Mutation, + ) => boolean +} + +/** + * Resolves an option that can be given either as a value or as a function of the query, such as + * `staleTime`. + * @param value - The option value, or a function that receives `query` and returns the value. + * @param query - The query passed to `value` if it is a function. + * @returns The resolved value, or `undefined` if `value` is `undefined`. + */ +export function resolveQueryValue< + TValue, + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + value: + | undefined + | TValue + | ((query: Query) => TValue), + query: Query, +): TValue | undefined { + return typeof value === 'function' + ? ( + value as ( + query: Query, + ) => TValue + )(query) + : value +} + +/** + * Checks whether a query matches the given {@link QueryFilters}. + * Every filter that is specified must match; filters that are left unspecified are ignored. + * @param filters - The filters to check the query against. + * @param query - The query to check. + * @param keyConfig - The cache configuration for key comparison and hashing. + * @returns `true` if the query matches every specified filter. + * @example + * ```ts + * const queryCache = getQueryCache(queryClient) + * + * const matchingQueries = queryCache + * .getAll() + * .filter((query) => matchQuery({ queryKey: ['posts'] }, query)) + * ``` + */ +export function matchQuery( + filters: QueryFilters, + query: Query, + keyConfig?: CacheKeyConfig, +): boolean { + const { + type = 'all', + exact, + fetchStatus, + predicate, + queryKey, + stale, + } = filters + + if (queryKey) { + if (exact) { + if (query.queryHash !== hashKeyByOptions(queryKey, keyConfig)) { + return false + } + } else if ( + !partialMatchKey(query.queryKey, queryKey, keyConfig?.equalityFn) + ) { + return false + } + } + + if (type !== 'all') { + const isActive = query.isActive() + if (type === 'active' && !isActive) { + return false + } + if (type === 'inactive' && isActive) { + return false + } + } + + if (typeof stale === 'boolean' && query.isStale() !== stale) { + return false + } + + if (fetchStatus && fetchStatus !== query.state.fetchStatus) { + return false + } + + if (predicate && !predicate(query)) { + return false + } + + return true +} + +/** + * Checks whether a mutation matches the given {@link MutationFilters}. + * Every filter that is specified must match; filters that are left unspecified are ignored. + * If a `mutationKey` filter is provided but the mutation has no `mutationKey` of its own, it does not match. + * @param filters - The filters to check the mutation against. + * @param mutation - The mutation to check. + * @param keyConfig - The cache configuration for key comparison and hashing. + * @returns `true` if the mutation matches every specified filter. + * @example + * ```ts + * const mutationCache = getMutationCache(queryClient) + * + * const matchingMutations = mutationCache + * .getAll() + * .filter((mutation) => matchMutation({ mutationKey: ['addPost'] }, mutation)) + * ``` + */ +export function matchMutation( + filters: MutationFilters, + mutation: Mutation, + keyConfig?: CacheKeyConfig, +): boolean { + const { exact, status, predicate, mutationKey } = filters + if (mutationKey) { + if (!mutation.options.mutationKey) { + return false + } + if (exact) { + if ( + hashKeyByOptions(mutation.options.mutationKey, keyConfig) !== + hashKeyByOptions(mutationKey, keyConfig) + ) { + return false + } + } else if ( + !partialMatchKey( + mutation.options.mutationKey, + mutationKey, + keyConfig?.equalityFn, + ) + ) { + return false + } + } + + if (status && mutation.state.status !== status) { + return false + } + + if (predicate && !predicate(mutation)) { + return false + } + + return true +} + +/** + * Intended to be passed as a query's `placeholderData` option, for example + * `placeholderData: keepPreviousData`. Instead of resetting the query's data to `undefined` while a new + * query key is fetching, it keeps displaying the previously fetched data until the new data arrives. + * @param previousData - The data of the previous query key, passed by the observer. + * @returns The previous data, unchanged. + * @example + * ```ts + * new QueryObserver(queryClient, { + * queryKey: ['posts', page], + * queryFn: () => fetchPosts(page), + * placeholderData: keepPreviousData, + * }) + * ``` + */ +export const keepPreviousData: ( + previousData: T | undefined, +) => T | undefined = identity + +/** + * Returns the function to call for a fetch. If there is no `queryFn` but the fetch was started from + * an `initialPromise`, that promise is returned instead. If there is no usable `queryFn`, the returned + * function rejects with a `Missing queryFn` error. + * @param options - The query options with the `queryFn`, and the `queryHash` used in error messages. + * @param fetchOptions - The fetch options, which may carry an `initialPromise`. + * @returns The function to call for the fetch. + */ +export function ensureQueryFn< + TQueryFnData = unknown, + TQueryKey extends QueryKey = QueryKey, +>( + options: { + queryFn?: + | QueryFunction + | SkipToken + | DefaultQueryFn + queryHash?: string + }, + fetchOptions?: FetchOptions, +): QueryFunction { + if (process.env.NODE_ENV !== 'production') { + if (options.queryFn === skipToken) { + console.error( + `Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${options.queryHash}'`, + ) + } + } + + // if we attempt to retry a fetch that was triggered from an initialPromise + // when we don't have a queryFn yet, we can't retry, so we just return the already rejected initialPromise + // if an observer has already mounted, we will be able to retry with that queryFn + if (!options.queryFn && fetchOptions?.initialPromise) { + return () => fetchOptions.initialPromise! + } + + if ( + !options.queryFn || + options.queryFn === skipToken || + options.queryFn === defaultQueryFn + ) { + return () => + Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`)) + } + + return options.queryFn +} + +export { + addConsumeAwareSignal, + addToArray, + defaultQueryFn, + fetchSignal, + functionalUpdate, + hashKey, + hashKeyByOptions, + isPlainArray, + isPlainObject, + isValidTimeout, + noop, + partialMatchKey, + replaceData, + replaceEqualDeep, + shallowEqualObjects, + shouldThrowError, + skipToken, + sleep, + timeUntilStale, +} from '@tanstack/query-core/primitives' +export type { + DefaultQueryFn, + FetchSignalContext, + QueryTypeFilter, + SkipToken, + Updater, +} from '@tanstack/query-core/primitives' diff --git a/packages/react-query-pluggable/src/suspense.ts b/packages/react-query-pluggable/src/suspense.ts new file mode 100644 index 00000000000..e2d79baf4c6 --- /dev/null +++ b/packages/react-query-pluggable/src/suspense.ts @@ -0,0 +1,215 @@ +import { use } from 'react' +import { getQueryCache } from './runtime/queryClient' +import { QueryObserver } from './runtime/queryObserver' +import type { + DefaultError, + QueryKey, + QueryObserverResult, +} from '@tanstack/query-core' +import type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary' +import type { Query } from './runtime/query' +import type { QueryClient } from './runtime/queryClient' +import type { DefaultedQueryObserverOptions } from './runtime/types' + +type SuspensePromiseEntry = { + fetchPromise: Promise + promise: Promise + settled: boolean +} + +const suspensePromiseCache = new WeakMap< + Query, + SuspensePromiseEntry +>() + +/** + * Uses the nearest error boundary when the query has no data to show. + * @param _error - The query error. + * @param query - The query that failed. + * @returns Whether the query has no data. + */ +export const defaultThrowOnError = < + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + _error: TError, + query: Query, +) => query.state.data === undefined + +/** + * Raises `staleTime` and a numeric `gcTime` to at least 1000ms when `suspense` is enabled, so a + * component that remounts after suspending doesn't refetch right away or find the query garbage + * collected. A `'static'` `staleTime` is kept as is. Mutates the options. + * @param defaultedOptions - The defaulted query options to adjust. + */ +export const ensureSuspenseTimers = ( + defaultedOptions: DefaultedQueryObserverOptions, +) => { + if (defaultedOptions.suspense) { + // Handle staleTime to ensure minimum 1000ms in Suspense mode + // This prevents unnecessary refetching when components remount after suspending + const MIN_SUSPENSE_TIME_MS = 1000 + + const clamp = (value: number | 'static' | undefined) => + value === 'static' + ? value + : Math.max(value ?? MIN_SUSPENSE_TIME_MS, MIN_SUSPENSE_TIME_MS) + + const originalStaleTime = defaultedOptions.staleTime + defaultedOptions.staleTime = + typeof originalStaleTime === 'function' + ? (...args) => clamp(originalStaleTime(...args)) + : clamp(originalStaleTime) + + if (typeof defaultedOptions.gcTime === 'number') { + defaultedOptions.gcTime = Math.max( + defaultedOptions.gcTime, + MIN_SUSPENSE_TIME_MS, + ) + } + } +} + +/** + * Decides whether a Suspense query needs to fetch during render. + * @param result - The result for this render. + * @param errorResetBoundary - The nearest query error reset boundary. + * @param query - The query to fetch. + * @returns `undefined` to skip the fetch, `false` to fetch in the background, or `true` to suspend. + */ +const shouldSuspend = ( + result: QueryObserverResult, + errorResetBoundary: QueryErrorResetBoundaryValue, + query: Query, +): boolean | undefined => { + if ( + result.isPending || + (query.state.status === 'error' && errorResetBoundary.isReset()) + ) { + return true + } + + if (result.isFetching && result.isPlaceholderData) { + return false + } + + return undefined +} + +/** + * Starts a fetch during render or reuses a promise for an existing fetch. + * @param defaultedOptions - The options of the query. + * @param observer - The observer that starts the fetch. + * @param errorResetBoundary - The nearest query error reset boundary. + * @param query - The query used to key the promise cache. + * @returns A promise that resolves when the fetch settles. + */ +export function getSuspensePromise( + defaultedOptions: DefaultedQueryObserverOptions, + observer: QueryObserver, + errorResetBoundary: QueryErrorResetBoundaryValue, + query: Query, +): Promise { + let entry = suspensePromiseCache.get(query) + if (!entry || entry.settled) { + const fetchPromise = observer.fetchOptimistic(defaultedOptions) + const settle = () => { + pending.settled = true + } + const pending: SuspensePromiseEntry = { + fetchPromise, + // Retry the render when the fetch settles, even on failure. + promise: fetchPromise.then(settle, settle), + settled: false, + } + suspensePromiseCache.set(query, pending) + entry = pending + } + + entry.fetchPromise.catch(() => errorResetBoundary.clearReset()) + return entry.promise +} + +type SuspenseOptions = DefaultedQueryObserverOptions +type SuspenseResult = QueryObserverResult +type SnapshotReader = { getSnapshot: () => T } + +const useReadSuspenseQuery = ( + defaultedOptions: SuspenseOptions, + reader: SnapshotReader, + observer: QueryObserver, + client: QueryClient, + errorResetBoundary: QueryErrorResetBoundaryValue, +) => { + if (!defaultedOptions.suspense) return + + const snapshot = reader.getSnapshot() + const query = getQueryCache(client).build(client, defaultedOptions) + const suspend = shouldSuspend(snapshot, errorResetBoundary, query) + if (suspend === undefined) return + + const promise = getSuspensePromise( + defaultedOptions, + observer, + errorResetBoundary, + query, + ) + if (suspend) { + use(promise) + } +} + +/** Supplies Suspense behavior for one query. */ +export const suspenseQueryPolicy = { + prepare: ensureSuspenseTimers, + readQuery: useReadSuspenseQuery, +} + +const useReadSuspenseQueries = ( + defaultedQueries: Array, + reader: SnapshotReader>, + client: QueryClient, + errorResetBoundary: QueryErrorResetBoundaryValue, +) => { + const snapshot = reader.getSnapshot() + + const suspensePromises = snapshot.map((result, index) => { + const opts = defaultedQueries[index] + + if (!opts?.suspense) { + return undefined + } + + const query = getQueryCache(client).build(client, opts) + const suspend = shouldSuspend(result, errorResetBoundary, query) + + if (suspend === undefined) { + return undefined + } + + const queryObserver = new QueryObserver(client, opts) + const promise = getSuspensePromise( + opts, + queryObserver, + errorResetBoundary, + query, + ) + + return suspend ? promise : undefined + }) + + // Start every fetch before calling use(), because use() suspends immediately. + for (const promise of suspensePromises) { + if (promise) { + use(promise) + } + } +} + +/** Supplies Suspense behavior for parallel queries. */ +export const suspenseQueriesPolicy = { + prepare: ensureSuspenseTimers, + readQueries: useReadSuspenseQueries, +} diff --git a/packages/react-query-pluggable/src/suspenseQuery.ts b/packages/react-query-pluggable/src/suspenseQuery.ts new file mode 100644 index 00000000000..c9e33daff0f --- /dev/null +++ b/packages/react-query-pluggable/src/suspenseQuery.ts @@ -0,0 +1,87 @@ +import { skipToken } from '@tanstack/query-core/primitives' +import { defaultThrowOnError, suspenseQueryPolicy } from './suspense' +import type { DefaultError, QueryKey, SkipToken } from '@tanstack/query-core' +import type { InfiniteQueryMode } from './infiniteQuery' +import type { UseSuspenseQueryOptions } from './types' +import type { SkippableSuspenseQueryOptions } from './useSuspenseQuery' + +/** The render policy attached to options prepared with `suspenseQuery`. */ +export interface SuspenseQueryMode { + /** Skipping the query disables its Suspense policy for this render. */ + readonly renderPolicy: TSkippable extends true + ? typeof suspenseQueryPolicy | undefined + : typeof suspenseQueryPolicy +} + +/** Options that make a single enabled query read through React Suspense. */ +export type SuspenseQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey extends QueryKey, +> = UseSuspenseQueryOptions & + SuspenseQueryMode + +/** + * Applies the Suspense render policy to a paginated query. + * @param options - An infinite query prepared with `infiniteQuery`. + * @returns The same paginated options with the policy for a running or skipped query. + */ +export function suspenseQuery< + TOptions extends InfiniteQueryMode & { queryFn?: unknown }, +>( + options: TOptions, +): TOptions & + SuspenseQueryMode + +/** + * Lets `useQuery` suspend while fetching a query without data. A failed query + * without data throws to the nearest error boundary. An observer can reuse + * data already cached by a regular query with the same key. + * @param options - Query options. The Suspense policy controls enabled and throwOnError. + * @returns Options for `useQuery`. A running query returns defined data. + */ +export function suspenseQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: UseSuspenseQueryOptions, +): SuspenseQueryOptions + +/** + * Supports a query function that may be `skipToken`. + * @param options - Passing `skipToken` keeps the observer disabled. + * @returns Options for `useQuery`. A skipped query can return undefined data. + */ +export function suspenseQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: SkippableSuspenseQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey + >, +): SkippableSuspenseQueryOptions & + SuspenseQueryMode + +export function suspenseQuery( + options: TOptions, +): TOptions & { + readonly renderPolicy: typeof suspenseQueryPolicy | undefined + enabled?: boolean + throwOnError?: typeof defaultThrowOnError +} { + const enabled = options.queryFn !== skipToken + return { + ...options, + enabled, + throwOnError: defaultThrowOnError, + renderPolicy: enabled ? suspenseQueryPolicy : undefined, + } +} diff --git a/packages/react-query-pluggable/src/types.ts b/packages/react-query-pluggable/src/types.ts new file mode 100644 index 00000000000..c1a2e18a0ce --- /dev/null +++ b/packages/react-query-pluggable/src/types.ts @@ -0,0 +1,471 @@ +import type { + DefaultError, + DefinedInfiniteQueryObserverResult, + DefinedQueryObserverResult, + DistributiveOmit, + InfiniteData, + InfiniteQueryObserverPlaceholderResult, + InfiniteQueryObserverResult, + OmitKeyof, + Override, + QueryKey, + QueryObserverPlaceholderResult, + QueryObserverResult, +} from '@tanstack/query-core' +import type { SkipToken } from '@tanstack/query-core/primitives' +import type { + InfiniteQueryExecuteOptions, + InfiniteQueryObserverOptions, + MutateFunction, + MutationObserverOptions, + MutationObserverResult, + QueryExecuteOptions, + QueryObserverOptions, +} from './runtime/types' + +/** + * {@link UseBaseQueryOptions} with all type parameters set to `any`, useful when the specific types aren't + * relevant, e.g. when accepting options for any query in a helper function. + */ +export type AnyUseBaseQueryOptions = UseBaseQueryOptions< + any, + any, + any, + any, + any +> +/** + * The options shared by `useQuery` and `useSuspenseQuery`. Extends {@link QueryObserverOptions} + * with the React-specific `subscribed` option. + * @template TQueryFnData - The type your `queryFn` resolves to. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no + * `select` is used. + * @template TQueryData - The type of the data actually held in the query cache — the input to `select` and + * `placeholderData`. Defaults to, and is usually the same as, `TQueryFnData`. + * @template TQueryKey - The type of your `queryKey`. + */ +export interface UseBaseQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> extends QueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey +> { + /** + * Set this to `false` to unsubscribe this observer from updates to the query cache. + * @defaultValue true + */ + subscribed?: boolean +} + +/** + * The options accepted by `usePrefetchQuery` — everything you can pass to `fetchQuery`, with a + * required `queryFn`. Pass `defaultQueryFn` to use the client defaults. + * @template TQueryFnData - The type your `queryFn` resolves to. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no + * `select` is used. + * @template TQueryData - The type of the data actually held in the query cache — the input to `select` and + * `placeholderData`. Defaults to, and is usually the same as, `TQueryFnData`. + * @template TQueryKey - The type of your `queryKey`. + */ +export type UsePrefetchQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = DistributiveOmit< + QueryExecuteOptions, + 'queryFn' +> & { + /** + * Pass a query function or `defaultQueryFn` to use the client defaults. Prefetch hooks do not accept `skipToken`. + */ + queryFn: Exclude< + QueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >['queryFn'], + SkipToken | undefined + > +} + +/** + * The options accepted by `usePrefetchInfiniteQuery` — everything you can pass to `fetchInfiniteQuery(client, options)`, + * with a required `queryFn`. Pass `defaultQueryFn` to use the client defaults. + * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. Defaults to `InfiniteData`, + * the shape of all fetched pages plus their page params — a prefetch never reads `data` back out, so this + * parameter only matters if you reuse these options elsewhere with `select` applied. + * @template TQueryKey - The type of your `queryKey`. + * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page. + */ +export type UsePrefetchInfiniteQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> = DistributiveOmit< + InfiniteQueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + 'queryFn' +> & { + /** + * Pass a query function or `defaultQueryFn` to use the client defaults. Prefetch hooks do not accept `skipToken`. + */ + queryFn: Exclude< + InfiniteQueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >['queryFn'], + SkipToken | undefined + > +} + +/** + * {@link UseQueryOptions} with all type parameters set to `any`, useful when the specific types aren't + * relevant, e.g. when accepting options for any query in a helper function. + */ +export type AnyUseQueryOptions = UseQueryOptions +/** + * The options accepted by `useQuery`. Same as {@link UseBaseQueryOptions}, minus `suspense` (which + * `react-query` derives from which hook you call rather than exposing as an option). + * @template TQueryFnData - The type your `queryFn` resolves to. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no + * `select` is used. + * @template TQueryKey - The type of your `queryKey`. + */ +export interface UseQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> extends OmitKeyof< + UseBaseQueryOptions, + 'suspense' +> {} + +/** + * {@link UseSuspenseQueryOptions} with all type parameters set to `any`, useful when the specific types aren't + * relevant, e.g. when accepting options for any query in a helper function. + */ +export type AnyUseSuspenseQueryOptions = UseSuspenseQueryOptions< + any, + any, + any, + any +> +/** + * Options for a `useSuspenseQuery` call whose data is defined. The options match those of + * {@link UseQueryOptions} except for `throwOnError` and `enabled`. + * Use the other overload for a query function that can be `skipToken`. + * @template TQueryFnData - The type your `queryFn` resolves to. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no + * `select` is used. + * @template TQueryKey - The type of your `queryKey`. + */ +export interface UseSuspenseQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> extends OmitKeyof< + UseQueryOptions, + 'queryFn' | 'enabled' | 'throwOnError' +> { + /** + * The query function. Use `defaultQueryFn` to use the client's configured function. + */ + queryFn: Exclude< + UseQueryOptions['queryFn'], + SkipToken + > +} + +/** + * {@link UseInfiniteQueryOptions} with all type parameters set to `any`, useful when the specific types aren't + * relevant, e.g. when accepting options for any query in a helper function. + */ +export type AnyUseInfiniteQueryOptions = UseInfiniteQueryOptions< + any, + any, + any, + any, + any +> +/** + * The options accepted by `useInfiniteQuery`. Extends {@link InfiniteQueryObserverOptions} + * with the React-specific `subscribed` option, minus `suspense` (which + * `react-query` derives from which hook you call rather than exposing as an option). + * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData`, + * the shape of all fetched pages plus their page params. + * @template TQueryKey - The type of your `queryKey`. + * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page. + */ +export interface UseInfiniteQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> extends OmitKeyof< + InfiniteQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + 'suspense' +> { + /** + * Set this to `false` to unsubscribe this observer from updates to the query cache. + * @defaultValue true + */ + subscribed?: boolean +} + +/** + * {@link UseSuspenseInfiniteQueryOptions} with all type parameters set to `any`, useful when the specific types + * aren't relevant, e.g. when accepting options for any query in a helper function. + */ +export type AnyUseSuspenseInfiniteQueryOptions = + UseSuspenseInfiniteQueryOptions +/** + * The options accepted by `useSuspenseInfiniteQuery`. Same as {@link UseInfiniteQueryOptions}, except for + * `enabled` and `throwOnError`. If `placeholderData` provides data, the query can render while the fetch runs. + * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData`, + * the shape of all fetched pages plus their page params. + * @template TQueryKey - The type of your `queryKey`. + * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page. + */ +export interface UseSuspenseInfiniteQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> extends OmitKeyof< + UseInfiniteQueryOptions, + 'queryFn' | 'enabled' | 'throwOnError' +> { + /** + * The query function. Use `defaultQueryFn` to use the client defaults. Use the other overload when the function can be `skipToken`. + */ + queryFn: Exclude< + UseInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >['queryFn'], + SkipToken + > +} + +/** + * The result of `useQuery` when `initialData` isn't set — `data` may be `undefined` while the query is + * `pending`. Re-exports {@link QueryObserverResult}. `useInfiniteQuery` returns + * {@link UseInfiniteQueryResult} instead. + * @template TData - The type `data` ends up as after `select` runs. + * @template TError - The type of errors your `queryFn` may throw. + */ +export type UseBaseQueryResult< + TData = unknown, + TError = DefaultError, +> = QueryObserverResult + +/** + * The result of `useQuery`. Same as {@link UseBaseQueryResult}. + * @template TData - The type `data` ends up as after `select` runs. + * @template TError - The type of errors your `queryFn` may throw. + */ +export type UseQueryResult< + TData = unknown, + TError = DefaultError, +> = UseBaseQueryResult + +/** The result of `useSuspenseQuery`, including defined placeholder data when configured. */ +export type UseSuspenseQueryResult = + | DefinedQueryObserverResult + | QueryObserverPlaceholderResult + +/** + * The result of `useQuery` when `initialData` is set. The `data` is never `undefined` (unless a `select` changes `TData` to include `undefined`). + * Re-exports {@link DefinedQueryObserverResult}. + * @template TData - The type `data` ends up as after `select` runs. + * @template TError - The type of errors your `queryFn` may throw. + */ +export type DefinedUseQueryResult< + TData = unknown, + TError = DefaultError, +> = DefinedQueryObserverResult + +/** + * The result of `useInfiniteQuery` when `initialData` isn't set — `data` may be `undefined` while the query is + * `pending`. Re-exports {@link InfiniteQueryObserverResult}. + * @template TData - The type `data` ends up as after `select` runs. + * @template TError - The type of errors your `queryFn` may throw. + */ +export type UseInfiniteQueryResult< + TData = unknown, + TError = DefaultError, +> = InfiniteQueryObserverResult + +/** + * The result of `useInfiniteQuery` when `initialData` is set — `data` is never `undefined` (unless a + * `select` changes `TData` to include `undefined`). Re-exports {@link DefinedInfiniteQueryObserverResult} + *. + * @template TData - The type `data` ends up as after `select` runs. + * @template TError - The type of errors your `queryFn` may throw. + */ +export type DefinedUseInfiniteQueryResult< + TData = unknown, + TError = DefaultError, +> = DefinedInfiniteQueryObserverResult + +/** + * The result of `useSuspenseInfiniteQuery`, including defined placeholder data when configured. + * @template TData - The type `data` ends up as after `select` runs. + * @template TError - The type of errors your `queryFn` may throw. + */ +export type UseSuspenseInfiniteQueryResult< + TData = unknown, + TError = DefaultError, +> = + | DefinedInfiniteQueryObserverResult + | InfiniteQueryObserverPlaceholderResult + +/** + * {@link UseMutationOptions} with all type parameters set to `any`, useful when the specific types aren't + * relevant, e.g. when accepting options for any mutation in a helper function. + */ +export type AnyUseMutationOptions = UseMutationOptions +/** + * The options accepted by `useMutation`. Same as {@link MutationObserverOptions}, + * minus the internal `_defaulted` flag. + * @template TData - The type your mutation function resolves to. + * @template TError - The type of errors your mutation function may throw. + * @template TVariables - The type of the variable passed to `mutate`/`mutateAsync`. + * @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as + * their `onMutateResult` parameter — useful for optimistic-update rollback data. + */ +export interface UseMutationOptions< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> extends OmitKeyof< + MutationObserverOptions, + '_defaulted' +> {} + +/** + * The type of `mutate`, as returned by `useMutation`. Forwards the variables (and an optional per-call + * `onSuccess`/`onError`/`onSettled`) to the underlying `mutate` call. Fire-and-forget — errors are surfaced + * through the mutation result instead of being thrown by `mutate`, unless `throwOnError` makes `useMutation` + * rethrow them. + * @template TData - The type your mutation function resolves to. + * @template TError - The type of errors your mutation function may throw. + * @template TVariables - The type of the variable passed to `mutate`. + * @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as + * their `onMutateResult` parameter — useful for optimistic-update rollback data. + */ +export type UseMutateFunction< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = ( + ...args: Parameters< + MutateFunction + > +) => void + +/** + * The type of `mutateAsync`, as returned by `useMutation`. Similar to {@link UseMutateFunction}, but returns a + * promise which can be awaited. + * @template TData - The type your mutation function resolves to. + * @template TError - The type of errors your mutation function may throw. + * @template TVariables - The type of the variable passed to `mutateAsync`. + * @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as + * their `onMutateResult` parameter — useful for optimistic-update rollback data. + */ +export type UseMutateAsyncFunction< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = MutateFunction + +/** + * The result of `useMutation`. Same as {@link MutationObserverResult}, with + * `mutate` narrowed to the fire-and-forget {@link UseMutateFunction} signature, plus the added `mutateAsync`. + * @template TData - The type your mutation function resolves to. + * @template TError - The type of errors your mutation function may throw. + * @template TVariables - The type of the variable passed to `mutate`/`mutateAsync`. + * @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as + * their `onMutateResult` parameter — useful for optimistic-update rollback data. + */ +export type UseBaseMutationResult< + TData = unknown, + TError = DefaultError, + TVariables = unknown, + TOnMutateResult = unknown, +> = Override< + MutationObserverResult, + { mutate: UseMutateFunction } +> & { + /** + * Similar to `mutate`, but returns a promise which can be awaited. + */ + mutateAsync: UseMutateAsyncFunction< + TData, + TError, + TVariables, + TOnMutateResult + > +} + +/** + * The result of `useMutation`. Same as {@link UseBaseMutationResult}. + * @template TData - The type your mutation function resolves to. + * @template TError - The type of errors your mutation function may throw. + * @template TVariables - The type of the variable passed to `mutate`/`mutateAsync`. + * @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as + * their `onMutateResult` parameter — useful for optimistic-update rollback data. + */ +export type UseMutationResult< + TData = unknown, + TError = DefaultError, + TVariables = unknown, + TOnMutateResult = unknown, +> = UseBaseMutationResult diff --git a/packages/react-query-pluggable/src/useBaseQuery.ts b/packages/react-query-pluggable/src/useBaseQuery.ts new file mode 100644 index 00000000000..ed6254e6fb1 --- /dev/null +++ b/packages/react-query-pluggable/src/useBaseQuery.ts @@ -0,0 +1,153 @@ +'use client' +import * as React from 'react' +import { useIsRestoring } from './IsRestoringProvider' +import { useQueryClient } from './QueryClientProvider' +import { useQueryErrorResetBoundary } from './QueryErrorResetBoundary' +import { + ensurePreventErrorBoundaryRetry, + getHasError, + useClearResetErrorBoundary, +} from './errorBoundaryUtils' +import { defaultQueryOptions, getQueryCache } from './runtime/queryClient' +import { useObserverSnapshot } from './useObserverSnapshot' +import type { QueryKey, QueryObserverResult } from '@tanstack/query-core' +import type { QueryClient } from './runtime/queryClient' +import type { QueryObserver } from './runtime/queryObserver' +import type { suspenseQueryPolicy } from './suspense' +import type { UseBaseQueryOptions } from './types' + +/** + * Base implementation shared by `useQuery`, `useInfiniteQuery`, `useSuspenseQuery`, and + * `useSuspenseInfiniteQuery`. + * @param options - The options passed to the calling hook. + * @param Observer - The query observer class (`QueryObserver` or + * `InfiniteQueryObserver`). + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest + * context will be used. + * @param suspense - Render policy used by the dedicated Suspense hooks. + * @returns The query result, tracking which properties are read unless `notifyOnChangeProps` is + * set. + * @throws {Error} If `options` is not an object (outside production), or the query error when it should be + * thrown to the nearest error boundary (see `throwOnError`). While suspending, it throws a promise instead. + */ +export function useBaseQuery< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey extends QueryKey, +>( + options: UseBaseQueryOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + Observer: typeof QueryObserver, + queryClient?: QueryClient, + suspense?: typeof suspenseQueryPolicy, +): QueryObserverResult { + if (process.env.NODE_ENV !== 'production') { + if (typeof options !== 'object' || Array.isArray(options)) { + throw new Error( + 'Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object', + ) + } + } + + const isRestoring = useIsRestoring() + const errorResetBoundary = useQueryErrorResetBoundary() + const client = useQueryClient(queryClient) + const defaultedOptions = defaultQueryOptions(client, { + ...options, + suspense: !!suspense, + }) + + const query = getQueryCache(client).get< + TQueryFnData, + TError, + TQueryData, + TQueryKey + >(defaultedOptions.queryHash) + + if (process.env.NODE_ENV !== 'production') { + if (!defaultedOptions.queryFn) { + console.error( + `[${defaultedOptions.queryHash}]: No query function was provided or configured in the query defaults. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`, + ) + } + } + + const subscribed = options.subscribed !== false + + // Make sure results are optimistically set in fetching state before subscribing or updating options + defaultedOptions._optimisticResults = isRestoring + ? 'isRestoring' + : subscribed + ? 'optimistic' + : undefined + + suspense?.prepare(defaultedOptions) + ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary, query) + useClearResetErrorBoundary(errorResetBoundary) + + const createObserver = () => ({ + client, + Observer, + observer: new Observer( + client, + defaultedOptions, + ), + }) + const [saved, setSaved] = React.useState(createObserver) + let current = saved + if (current.Observer !== Observer || current.client !== client) { + current = createObserver() + setSaved(current) + } + const { observer } = current + + const reader = observer.createResultReader(defaultedOptions) + + suspense?.readQuery( + defaultedOptions, + reader, + observer, + client, + errorResetBoundary, + ) + + const result = useObserverSnapshot( + observer, + reader, + !isRestoring && subscribed, + refreshQuery, + ) + + // Handle error boundary + if ( + getHasError({ + result, + errorResetBoundary, + throwOnError: defaultedOptions.throwOnError, + query, + suspense: defaultedOptions.suspense, + }) + ) { + throw result.error + } + + // Handle result property usage tracking + return !defaultedOptions.notifyOnChangeProps + ? observer.trackResult(result) + : result +} + +/** + * Refreshes the query after the observer subscribes. + * @param observer - The observer that was subscribed. + */ +function refreshQuery(observer: Pick): void { + observer.updateResult() +} diff --git a/packages/react-query-pluggable/src/useInfiniteQuery.ts b/packages/react-query-pluggable/src/useInfiniteQuery.ts new file mode 100644 index 00000000000..3b2882b95e4 --- /dev/null +++ b/packages/react-query-pluggable/src/useInfiniteQuery.ts @@ -0,0 +1,356 @@ +'use client' + +import { infiniteQuery } from './infiniteQuery' +import { useQuery } from './useQuery' +import type { DefaultError, InfiniteData, QueryKey } from '@tanstack/query-core' +import type { + DefinedInitialDataInfiniteOptions, + UndefinedInitialDataInfiniteOptions, +} from './infiniteQueryOptions' +import type { QueryClient } from './runtime/queryClient' +import type { + DefinedUseInfiniteQueryResult, + UseInfiniteQueryOptions, + UseInfiniteQueryResult, +} from './types' + +/** + * The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of + * `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. + * + * This overload is selected when `initialData` is known to be defined. + * @param options - The {@link DefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`, with `initialData` known to be defined. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`, + * `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and + * `data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default + * `InfiniteData` shape. + * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default + * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user + * actions, or add conditions like `hasNextPage && !isFetching`. + * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `fetchInfiniteQuery(client, options)`. + * @example + * ```tsx + * import { useInfiniteQuery } from '@tanstack/react-query-pluggable' + * + * function Projects() { + * // `data` is never `undefined`, thanks to `initialData` — even if a refetch fails, so the + * // list stays visible alongside the error. + * const { data, isError, error } = useInfiniteQuery({ + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * initialData: { pages: [], pageParams: [] }, + * }) + * + * return ( + *
    + * {isError ? Error: {error.message} : null} + *
      + * {data.pages.map((page) => page.projects.map((p) =>
    • {p.name}
    • ))} + *
    + *
    + * ) + * } + * ``` + */ +export function useInfiniteQuery< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + options: DefinedInitialDataInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + queryClient?: QueryClient, +): DefinedUseInfiniteQueryResult + +/** + * The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of + * `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. + * @param options - The {@link UndefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`, + * `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and + * `data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default + * `InfiniteData` shape. + * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default + * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user + * actions, or add conditions like `hasNextPage && !isFetching`. + * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `fetchInfiniteQuery(client, options)`. + * @example + * Fetching the next page from a "Load More" button click: + * ```tsx + * import { useInfiniteQuery } from '@tanstack/react-query-pluggable' + * + * function Projects() { + * const { data, isPending, isError, error, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage } = + * useInfiniteQuery({ + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return ( + * <> + *
      + * {data.pages.map((page) => + * page.projects.map((project) =>
    • {project.name}
    • ), + * )} + *
    + * + * + * ) + * } + * ``` + * @example + * Fetching the next page automatically as the user scrolls, using an `IntersectionObserver` on a + * sentinel element after the list: + * ```tsx + * import { useInfiniteQuery } from '@tanstack/react-query-pluggable' + * import { useEffect, useRef } from 'react' + * + * function Projects() { + * const { + * data, + * isPending, + * isError, + * error, + * fetchNextPage, + * hasNextPage, + * isFetching, + * isFetchingNextPage, + * } = useInfiniteQuery({ + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * const sentinelRef = useRef(null) + * + * useEffect(() => { + * const sentinel = sentinelRef.current + * if (sentinel == null || !hasNextPage || isFetching) return + * + * const observer = new IntersectionObserver(([entry]) => { + * if (entry?.isIntersecting) fetchNextPage() + * }) + * observer.observe(sentinel) + * + * return () => observer.disconnect() + * }, [hasNextPage, isFetching, fetchNextPage]) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return ( + * <> + *
      + * {data.pages.map((page) => + * page.projects.map((project) =>
    • {project.name}
    • ), + * )} + *
    + *
    {isFetchingNextPage ? 'Loading more...' : null}
    + * + * ) + * } + * ``` + */ +export function useInfiniteQuery< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + options: UndefinedInitialDataInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + queryClient?: QueryClient, +): UseInfiniteQueryResult + +/** + * The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of + * `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. + * @param options - The {@link UseInfiniteQueryOptions} to use — everything you can pass to `useInfiniteQuery`. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`, + * `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and + * `data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default + * `InfiniteData` shape. + * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default + * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user + * actions, or add conditions like `hasNextPage && !isFetching`. + * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `fetchInfiniteQuery(client, options)`. + * @example + * Fetching the next page from a "Load More" button click: + * ```tsx + * import { useInfiniteQuery } from '@tanstack/react-query-pluggable' + * + * function Projects() { + * const { data, isPending, isError, error, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage } = + * useInfiniteQuery({ + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return ( + * <> + *
      + * {data.pages.map((page) => + * page.projects.map((project) =>
    • {project.name}
    • ), + * )} + *
    + * + * + * ) + * } + * ``` + * @example + * Fetching the next page automatically as the user scrolls, using an `IntersectionObserver` on a + * sentinel element after the list: + * ```tsx + * import { useInfiniteQuery } from '@tanstack/react-query-pluggable' + * import { useEffect, useRef } from 'react' + * + * function Projects() { + * const { + * data, + * isPending, + * isError, + * error, + * fetchNextPage, + * hasNextPage, + * isFetching, + * isFetchingNextPage, + * } = useInfiniteQuery({ + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * const sentinelRef = useRef(null) + * + * useEffect(() => { + * const sentinel = sentinelRef.current + * if (sentinel == null || !hasNextPage || isFetching) return + * + * const observer = new IntersectionObserver(([entry]) => { + * if (entry?.isIntersecting) fetchNextPage() + * }) + * observer.observe(sentinel) + * + * return () => observer.disconnect() + * }, [hasNextPage, isFetching, fetchNextPage]) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return ( + * <> + *
      + * {data.pages.map((page) => + * page.projects.map((project) =>
    • {project.name}
    • ), + * )} + *
    + *
    {isFetchingNextPage ? 'Loading more...' : null}
    + * + * ) + * } + * ``` + * @example + * A query that's disabled, type safe, until `postId` is set — pass `skipToken` as `queryFn` + * instead of setting `enabled: false`: + * ```tsx + * import { skipToken, useInfiniteQuery } from '@tanstack/react-query-pluggable' + * + * function Comments({ postId }: { postId: string | undefined }) { + * // Use `isLoading`, not `isPending`, so the loading state doesn't show while the query is disabled. + * const { data, isLoading, isError, error } = useInfiniteQuery({ + * queryKey: ['post', postId, 'comments'], + * queryFn: + * postId != null + * ? ({ pageParam }) => fetchComments(postId, pageParam) + * : skipToken, + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * if (postId == null) return 'Select a post' + * if (isLoading) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return ( + *
      + * {data?.pages.map((page) => page.comments.map((c) =>
    • {c.text}
    • ))} + *
    + * ) + * } + * ``` + */ +export function useInfiniteQuery< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + options: UseInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + queryClient?: QueryClient, +): UseInfiniteQueryResult + +export function useInfiniteQuery( + options: UseInfiniteQueryOptions, + queryClient?: QueryClient, +) { + return useQuery(infiniteQuery(options), queryClient) +} diff --git a/packages/react-query-pluggable/src/useIsFetching.ts b/packages/react-query-pluggable/src/useIsFetching.ts new file mode 100644 index 00000000000..bd98c21423f --- /dev/null +++ b/packages/react-query-pluggable/src/useIsFetching.ts @@ -0,0 +1,58 @@ +'use client' +import * as React from 'react' +import { useQueryClient } from './QueryClientProvider' +import { notifyManager } from './runtime/notifyManager' +import { getQueryCache, isFetching } from './runtime/queryClient' +import type { QueryClient } from './runtime/queryClient' +import type { QueryFilters } from './runtime/utils' + +/** + * The `useIsFetching` hook returns the `number` of the queries that your application is loading or fetching in + * the background (useful for app-wide loading indicators). + * @param filters - The {@link QueryFilters} to narrow down the matched queries. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns Will be the `number` of the queries that your application is currently loading or fetching in the + * background. + * @example + * ```tsx + * import { useIsFetching } from '@tanstack/react-query-pluggable' + * + * function PostsFetchingIndicator() { + * // How many queries matching the posts prefix are fetching? + * const isFetchingPosts = useIsFetching({ queryKey: ['posts'] }) + * + * return isFetchingPosts ? Refreshing posts... : null + * } + * ``` + * @example + * A global loading indicator for any query fetching in the background, not just the ones on screen: + * ```tsx + * import { useIsFetching } from '@tanstack/react-query-pluggable' + * + * function GlobalLoadingIndicator() { + * const isFetching = useIsFetching() + * + * return isFetching ? ( + *
    Queries are fetching in the background...
    + * ) : null + * } + * ``` + */ +export function useIsFetching( + filters?: Omit, + queryClient?: QueryClient, +): number { + const client = useQueryClient(queryClient) + const queryCache = getQueryCache(client) + + return React.useSyncExternalStore( + React.useCallback( + (onStoreChange) => + queryCache.subscribe(notifyManager.batchCalls(onStoreChange)), + [queryCache], + ), + () => isFetching(client, filters), + () => isFetching(client, filters), + ) +} diff --git a/packages/react-query-pluggable/src/useMutation.ts b/packages/react-query-pluggable/src/useMutation.ts new file mode 100644 index 00000000000..7e15fcc17f9 --- /dev/null +++ b/packages/react-query-pluggable/src/useMutation.ts @@ -0,0 +1,240 @@ +'use client' + +import { noop, shouldThrowError } from '@tanstack/query-core/primitives' +import * as React from 'react' +import { useQueryClient } from './QueryClientProvider' +import { MutationObserver } from './runtime/mutationObserver' +import { notifyManager } from './runtime/notifyManager' +import type { DefaultError } from '@tanstack/query-core' +import type { QueryClient } from './runtime/queryClient' +import type { + UseMutateFunction, + UseMutationOptions, + UseMutationResult, +} from './types' + +// HOOK + +/** + * Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects. + * `useMutation` is the hook for that. + * @param options - The {@link UseMutationOptions} to use — everything you can pass to `useMutation`. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns `mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a second + * argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to the shared + * mutation definition. Hook-level callbacks (passed to `options`) fire for every mutation; per-call callbacks + * fire only for the latest call you've made, and only while the component is still mounted — unmounting before + * the mutation settles removes the subscription and prevents them from firing. + * @throws {Error} The mutation error, when `throwOnError` is `true` or returns `true` for it, so that it is + * thrown to the nearest error boundary. + * @see {@link mutationOptions} to share these options across multiple `useMutation` call sites, or to look + * the mutation up elsewhere via its `mutationKey` (e.g. with `useMutationState`). + * @example + * ```tsx + * import { useMutation, useQueryClient, invalidateQueries } from '@tanstack/react-query-pluggable' + * + * function AddTodo() { + * const queryClient = useQueryClient() + * + * const addMutation = useMutation({ + * mutationFn: addTodo, + * onSuccess: () => invalidateQueries(queryClient, { queryKey: ['todos'] }), + * }) + * + * return ( + * + * ) + * } + * ``` + * @example + * Rendering the mutation's own state, rather than just firing it off: + * ```tsx + * import { useMutation, useQueryClient, invalidateQueries } from '@tanstack/react-query-pluggable' + * + * function AddTodo() { + * const queryClient = useQueryClient() + * + * const addMutation = useMutation({ + * mutationFn: addTodo, + * onSuccess: () => invalidateQueries(queryClient, { queryKey: ['todos'] }), + * }) + * + * return ( + *
    + * {addMutation.isPending ? ( + * 'Adding todo...' + * ) : ( + * <> + * {addMutation.isError ? ( + *
    An error occurred: {addMutation.error.message}
    + * ) : null} + * + * + * )} + *
    + * ) + * } + * ``` + * @example + * Optimistic update via `onMutate`, rolling back on `onError`: + * ```tsx + * import { useMutation, useQueryClient, cancelQueries, getQueryData, setQueryData, invalidateQueries } from '@tanstack/react-query-pluggable' + * + * function AddTodo() { + * const queryClient = useQueryClient() + * + * const addMutation = useMutation({ + * mutationFn: addTodo, + * onMutate: async (newTodo) => { + * await cancelQueries(queryClient, { queryKey: ['todos'] }) + * const previousTodos = getQueryData(queryClient, ['todos']) + * + * setQueryData(queryClient, ['todos'], (old) => [ + * ...(old ?? []), + * newTodo, + * ]) + * + * // Passed to `onError` as `onMutateResult` if the mutation fails. + * return { previousTodos } + * }, + * onError: (_err, _newTodo, onMutateResult) => { + * setQueryData(queryClient, ['todos'], onMutateResult?.previousTodos) + * }, + * onSettled: () => { + * invalidateQueries(queryClient, { queryKey: ['todos'] }) + * }, + * }) + * + * return ( + * + * ) + * } + * ``` + * @example + * Callbacks passed per call to `mutate` only fire for the last call — `mutateAsync` gives you a + * promise per call instead, so you can wait for all of them when they succeed: + * ```tsx + * import { useMutation, useQueryClient, invalidateQueries } from '@tanstack/react-query-pluggable' + * + * function AddTodos() { + * const queryClient = useQueryClient() + * + * const addMutation = useMutation({ + * mutationFn: addTodo, + * onSuccess: () => invalidateQueries(queryClient, { queryKey: ['todos'] }), + * }) + * + * async function handleAddAll(todos: Array) { + * try { + * await Promise.all(todos.map((todo) => addMutation.mutateAsync(todo))) + * } catch (error) { + * console.error('Failed to add todos:', error) + * } + * } + * + * return ( + * + * ) + * } + * ``` + * @example + * If some of the mutations above can fail independently of the others, and you want to know which ones + * did — rather than losing that information the moment the first one rejects — swap `Promise.all` for + * `Promise.allSettled`: + * ```tsx + * import { useMutation, useQueryClient, invalidateQueries } from '@tanstack/react-query-pluggable' + * + * function AddTodos() { + * const queryClient = useQueryClient() + * + * const addMutation = useMutation({ + * mutationFn: addTodo, + * onSuccess: () => invalidateQueries(queryClient, { queryKey: ['todos'] }), + * }) + * + * async function handleAddAll(todos: Array) { + * const addResults = await Promise.allSettled( + * todos.map((todo) => addMutation.mutateAsync(todo)), + * ) + * + * addResults.forEach((addResult, index) => { + * if (addResult.status === 'rejected') { + * console.error(`Failed to add "${todos[index]}":`, addResult.reason) + * } + * }) + * } + * + * return ( + * + * ) + * } + * ``` + */ +export function useMutation< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +>( + options: UseMutationOptions, + queryClient?: QueryClient, +): UseMutationResult { + const client = useQueryClient(queryClient) + + const [observer] = React.useState( + () => + new MutationObserver( + client, + options, + ), + ) + + React.useEffect(() => { + observer.setOptions(options) + }, [observer, options]) + + const result = React.useSyncExternalStore( + React.useCallback( + (onStoreChange) => + observer.subscribe(notifyManager.batchCalls(onStoreChange)), + [observer], + ), + () => observer.getCurrentResult(), + () => observer.getCurrentResult(), + ) + + const mutate = React.useCallback< + UseMutateFunction + >( + ( + ...args: Parameters< + UseMutateFunction + > + ) => { + observer.mutate(args[0] as TVariables, args[1]).catch(noop) + }, + [observer], + ) + + if ( + result.error && + shouldThrowError(observer.options.throwOnError, [result.error]) + ) { + throw result.error + } + + return { ...result, mutate, mutateAsync: result.mutate } +} diff --git a/packages/react-query-pluggable/src/useMutationState.ts b/packages/react-query-pluggable/src/useMutationState.ts new file mode 100644 index 00000000000..f5f06adfe8b --- /dev/null +++ b/packages/react-query-pluggable/src/useMutationState.ts @@ -0,0 +1,206 @@ +'use client' + +import { replaceEqualDeep } from '@tanstack/query-core/primitives' +import * as React from 'react' +import { useQueryClient } from './QueryClientProvider' +import { getMutationCache } from './runtime/mutationCache' +import { notifyManager } from './runtime/notifyManager' +import type { MutationState } from '@tanstack/query-core' +import type { Mutation } from './runtime/mutation' +import type { MutationCache } from './runtime/mutationCache' +import type { QueryClient } from './runtime/queryClient' +import type { MutationFilters } from './runtime/utils' + +/** + * The `useIsMutating` hook returns the `number` of mutations that your application currently has `pending` + * (useful for app-wide loading indicators). + * @param filters - The {@link MutationFilters} to narrow down the matched mutations. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns Will be the `number` of the mutations that your application currently has `pending`. + * @example + * ```tsx + * import { useIsMutating } from '@tanstack/react-query-pluggable' + * + * function PostsMutatingIndicator() { + * // How many mutations matching the posts prefix are in progress? + * const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] }) + * + * return isMutatingPosts ? Saving posts... : null + * } + * ``` + */ +export function useIsMutating( + filters?: Omit, + queryClient?: QueryClient, +): number { + const client = useQueryClient(queryClient) + return useMutationState( + { filters: { ...filters, status: 'pending' } }, + client, + ).length +} + +type MutationTypeFromResult = [TResult] extends [ + MutationState< + infer TData, + infer TError, + infer TVariables, + infer TOnMutateResult + >, +] + ? Mutation + : Mutation + +type MutationStateOptions< + TResult = MutationState, + TMutation extends Mutation = + MutationTypeFromResult, +> = { + filters?: MutationFilters + select?: (mutation: TMutation) => TResult +} + +/** + * Creates snapshot getters that share equal selected results across renders. + * A new getter is created on each render. Each getter caches its snapshot until the matching mutations + * or their states change. + * @returns A factory for snapshot getters with a shared result cache. + */ +function createSnapshotFactory< + TResult = MutationState, + TMutation extends Mutation = + MutationTypeFromResult, +>() { + let previousResult: Array | undefined + + return ( + mutationCache: MutationCache, + options: MutationStateOptions, + ) => { + let inputs: Array = [] + let snapshot: Array | undefined + + return (): Array => { + const mutations = mutationCache.findAll(options.filters) + const nextInputs = mutations.flatMap((mutation) => [ + mutation, + mutation.state, + ]) + + if ( + !snapshot || + nextInputs.length !== inputs.length || + nextInputs.some((input, index) => !Object.is(input, inputs[index])) + ) { + inputs = nextInputs + snapshot = replaceEqualDeep( + previousResult, + mutations.map( + (mutation): TResult => + (options.select + ? options.select(mutation as TMutation) + : mutation.state) as TResult, + ), + ) + previousResult = snapshot + } + + return snapshot + } + } +} + +/** + * `useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass + * `filters` ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the mutation + * state. + * @param options - The `filters` to narrow down matched mutations, and an optional `select` to transform the + * mutation state. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns Will be an Array of whatever `select` returns for each matching mutation. + * @example + * Get all variables of all running mutations: + * ```tsx + * import { useMutationState } from '@tanstack/react-query-pluggable' + * + * function PendingPosts() { + * const pendingVariables = useMutationState({ + * filters: { status: 'pending' }, + * select: (mutation) => mutation.state.variables, + * }) + * + * return <>{pendingVariables.length} posts saving... + * } + * ``` + * @example + * Get all data for specific mutations via the `mutationKey`: + * ```tsx + * import { useMutation, useMutationState } from '@tanstack/react-query-pluggable' + * + * const mutationKey = ['posts'] + * + * function Posts() { + * // Some mutation that we want to get the state for + * const mutation = useMutation({ + * mutationKey, + * mutationFn: createPosts, + * }) + * + * const savedPosts = useMutationState({ + * // this mutation key needs to match the mutation key of the given mutation (see above) + * filters: { mutationKey, status: 'success' }, + * select: (mutation) => mutation.state.data, + * }) + * + * return ( + * + * ) + * } + * ``` + * @example + * Access the latest successful mutation data via the `mutationKey`. Each invocation of `mutate` adds a new + * entry to the mutation cache for `gcTime` milliseconds — with the `status: 'success'` filter below, check the + * last item that `useMutationState` returns to get the latest successful invocation: + * ```tsx + * import { useMutationState } from '@tanstack/react-query-pluggable' + * + * function LatestPost() { + * const savedPosts = useMutationState({ + * filters: { mutationKey: ['posts'], status: 'success' }, + * select: (mutation) => mutation.state.data, + * }) + * + * const latestSavedPost = savedPosts[savedPosts.length - 1] + * + * return <>{latestSavedPost ? 'Saved' : 'Nothing saved yet'} + * } + * ``` + */ +export function useMutationState< + TResult = MutationState, + TMutation extends Mutation = + MutationTypeFromResult, +>( + options: MutationStateOptions = {}, + queryClient?: QueryClient, +): Array { + const mutationCache = getMutationCache(useQueryClient(queryClient)) + const [createSnapshot] = React.useState(() => + createSnapshotFactory(), + ) + const getSnapshot = createSnapshot(mutationCache, options) + + return React.useSyncExternalStore( + React.useCallback( + (onStoreChange) => + mutationCache.subscribe(notifyManager.batchCalls(onStoreChange)), + [mutationCache], + ), + getSnapshot, + getSnapshot, + ) +} diff --git a/packages/react-query-pluggable/src/useObserverSnapshot.ts b/packages/react-query-pluggable/src/useObserverSnapshot.ts new file mode 100644 index 00000000000..216594a18cc --- /dev/null +++ b/packages/react-query-pluggable/src/useObserverSnapshot.ts @@ -0,0 +1,43 @@ +'use client' +import { noop } from '@tanstack/query-core/primitives' +import * as React from 'react' +import { notifyManager } from './runtime/notifyManager' +import type { QueryObserverResultReader } from './runtime/queryObserver' + +interface ObserverStore { + subscribe: (listener: () => void) => () => void +} + +/** + * Commits a reader and subscribes React to its cached snapshots. + * @param observer - The observer that owns the subscription. + * @param reader - The reader scoped to the current render options. + * @param subscribed - Whether this render subscribes to updates. + * @param refresh - Includes updates that occurred before the subscription started. + * @returns The current snapshot. + */ +export function useObserverSnapshot( + observer: TObserver, + reader: QueryObserverResultReader, + subscribed: boolean, + refresh: (observer: TObserver) => void, +): TResult { + React.useEffect(() => { + reader.commit() + }, [reader]) + + return React.useSyncExternalStore( + React.useCallback( + (onStoreChange) => { + const unsubscribe = subscribed + ? observer.subscribe(notifyManager.batchCalls(onStoreChange)) + : noop + refresh(observer) + return unsubscribe + }, + [observer, subscribed, refresh], + ), + reader.getSnapshot, + reader.getSnapshot, + ) +} diff --git a/packages/react-query-pluggable/src/usePrefetchInfiniteQuery.tsx b/packages/react-query-pluggable/src/usePrefetchInfiniteQuery.tsx new file mode 100644 index 00000000000..05d833a7346 --- /dev/null +++ b/packages/react-query-pluggable/src/usePrefetchInfiniteQuery.tsx @@ -0,0 +1,70 @@ +import { noop } from '@tanstack/query-core/primitives' +import { useQueryClient } from './QueryClientProvider' +import { fetchInfiniteQuery } from './runtime/fetchInfiniteQuery' +import { getQueryState } from './runtime/queryClient' +import type { DefaultError, InfiniteData, QueryKey } from '@tanstack/query-core' +import type { QueryClient } from './runtime/queryClient' +import type { UsePrefetchInfiniteQueryOptions } from './types' + +/** + * `usePrefetchInfiniteQuery` does not return anything, it should be used just to fire a prefetch during render, + * before a suspense boundary that wraps a component that uses `useSuspenseInfiniteQuery`. You can pass + * everything to `usePrefetchInfiniteQuery` that you can pass to `fetchInfiniteQuery(client, options)`, though + * `queryKey`, `initialPageParam`, and `getNextPageParam` are always required, and `queryFn` is required. Pass `defaultQueryFn` to use the client defaults. + * + * `getNextPageParam` receives both the last page of the infinite list of data and the full array of all pages, + * as well as pageParam information, and should return a single variable that will be passed to your query + * function as `context.pageParam`. Return `undefined` or `null` to indicate there is no next page available. + * + * The prefetch is skipped if the query already has any cached state — including a `pending`/`error` state left + * over from a previous attempt — so calling this on every render is cheap and won't refetch data that's + * already there or already in flight. + * @param options - The {@link UsePrefetchInfiniteQueryOptions} to use — everything you can pass to `fetchInfiniteQuery(client, options)`. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @example + * ```tsx + * import { Suspense } from 'react' + * import { infiniteQueryOptions, usePrefetchInfiniteQuery } from '@tanstack/react-query-pluggable' + * + * const projectsOptions = infiniteQueryOptions({ + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * function App() { + * // Fire the prefetch during render, before the suspense boundary below. + * usePrefetchInfiniteQuery(projectsOptions) + * + * return ( + * Loading projects...}> + * + * + * ) + * } + * ``` + */ +export function usePrefetchInfiniteQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + options: UsePrefetchInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + queryClient?: QueryClient, +): void { + const client = useQueryClient(queryClient) + + if (!getQueryState(client, options.queryKey)) { + void fetchInfiniteQuery(client, options).catch(noop) + } +} diff --git a/packages/react-query-pluggable/src/usePrefetchQuery.tsx b/packages/react-query-pluggable/src/usePrefetchQuery.tsx new file mode 100644 index 00000000000..43eca68bb73 --- /dev/null +++ b/packages/react-query-pluggable/src/usePrefetchQuery.tsx @@ -0,0 +1,61 @@ +import { noop } from '@tanstack/query-core/primitives' +import { useQueryClient } from './QueryClientProvider' +import { fetchQuery, getQueryState } from './runtime/queryClient' +import type { DefaultError, QueryKey } from '@tanstack/query-core' +import type { QueryClient } from './runtime/queryClient' +import type { UsePrefetchQueryOptions } from './types' + +/** + * `usePrefetchQuery` does not return anything, it should be used just to fire a prefetch during render, before + * a suspense boundary that wraps a component that uses `useSuspenseQuery`. You can pass everything to + * `usePrefetchQuery` that you can pass to `fetchQuery`, though `queryKey` is always required, and + * `queryFn` is required. Pass `defaultQueryFn` to use the client defaults. + * + * The prefetch is skipped if the query already has any cached state — including a `pending`/`error` state left + * over from a previous attempt — so calling this on every render is cheap and won't refetch data that's + * already there or already in flight. + * @param options - The {@link UsePrefetchQueryOptions} to use — everything you can pass to `fetchQuery`. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @example + * ```tsx + * import { Suspense } from 'react' + * import { usePrefetchQuery } from '@tanstack/react-query-pluggable' + * + * function App() { + * // Fire the prefetch during render, before the suspense boundary below. + * usePrefetchQuery({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * }) + * + * return ( + * Loading posts...}> + * + * + * ) + * } + * ``` + */ +export function usePrefetchQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: UsePrefetchQueryOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + queryClient?: QueryClient, +): void { + const client = useQueryClient(queryClient) + + if (!getQueryState(client, options.queryKey)) { + void fetchQuery(client, options).catch(noop) + } +} diff --git a/packages/react-query-pluggable/src/useQueries.ts b/packages/react-query-pluggable/src/useQueries.ts new file mode 100644 index 00000000000..0d437e0dd14 --- /dev/null +++ b/packages/react-query-pluggable/src/useQueries.ts @@ -0,0 +1,488 @@ +'use client' +import * as React from 'react' +import { useIsRestoring } from './IsRestoringProvider' +import { useQueryClient } from './QueryClientProvider' +import { useQueryErrorResetBoundary } from './QueryErrorResetBoundary' +import { + ensurePreventErrorBoundaryRetry, + getHasError, + useClearResetErrorBoundary, +} from './errorBoundaryUtils' +import { QueriesObserver } from './runtime/queriesObserver' +import { defaultQueryOptions, getQueryCache } from './runtime/queryClient' +import { useObserverSnapshot } from './useObserverSnapshot' +import type { + DefaultError, + OmitKeyof, + QueriesObserverOptions, + QueriesPlaceholderDataFunction, + QueryKey, +} from '@tanstack/query-core' +import type { placeholderData } from './runtime/placeholderData' +import type { Select } from './runtime/projectionTypes' +import type { QueryClient } from './runtime/queryClient' +import type { + QueryFunction, + QueryObserverOptions, + ThrowOnError, +} from './runtime/types' +import type { suspenseQueriesPolicy } from './suspense' +import type { + DefinedUseQueryResult, + UseQueryOptions, + UseQueryResult, +} from './types' + +// This defines the `UseQueryOptions` that are accepted in `QueriesOptions` & `GetOptions`. +// `placeholderData` function always gets undefined passed +type UseQueryOptionsForUseQueries< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = OmitKeyof< + UseQueryOptions, + 'placeholderData' | 'subscribed' +> & { + placeholderData?: readonly [ + typeof placeholderData, + TQueryFnData | QueriesPlaceholderDataFunction, + ] +} + +// Avoid TS depth-limit error in case of large array literal +type MAXIMUM_DEPTH = 20 + +// Widen the type of the symbol to enable type inference even if skipToken is not immutable. +type SkipTokenForUseQueries = symbol + +type GetUseQueryOptionsForUseQueries = + // Part 1: responsible for applying explicit type parameter to function arguments, if object { queryFnData: TQueryFnData, error: TError, data: TData } + T extends { + queryFnData: infer TQueryFnData + error?: infer TError + data: infer TData + } + ? UseQueryOptionsForUseQueries + : T extends { queryFnData: infer TQueryFnData; error?: infer TError } + ? UseQueryOptionsForUseQueries + : T extends { data: infer TData; error?: infer TError } + ? UseQueryOptionsForUseQueries + : // Part 2: responsible for applying explicit type parameter to function arguments, if tuple [TQueryFnData, TError, TData] + T extends [infer TQueryFnData, infer TError, infer TData] + ? UseQueryOptionsForUseQueries + : T extends [infer TQueryFnData, infer TError] + ? UseQueryOptionsForUseQueries + : T extends [infer TQueryFnData] + ? UseQueryOptionsForUseQueries + : // Part 3: responsible for inferring and enforcing type if no explicit parameter was provided + T extends { + queryFn?: + | QueryFunction + | SkipTokenForUseQueries + select?: Select + throwOnError?: ThrowOnError + } + ? UseQueryOptionsForUseQueries< + TQueryFnData, + unknown extends TError ? DefaultError : TError, + unknown extends TData ? TQueryFnData : TData, + TQueryKey + > + : // Fallback + UseQueryOptionsForUseQueries + +// A defined initialData setting should return a DefinedUseQueryResult rather than UseQueryResult +type GetDefinedOrUndefinedQueryResult = T extends { + initialData?: infer TInitialData +} + ? unknown extends TInitialData + ? UseQueryResult + : TInitialData extends TData + ? DefinedUseQueryResult + : TInitialData extends () => infer TInitialDataResult + ? unknown extends TInitialDataResult + ? UseQueryResult + : TInitialDataResult extends TData + ? DefinedUseQueryResult + : UseQueryResult + : UseQueryResult + : UseQueryResult + +type GetUseQueryResult = + // Part 1: responsible for mapping explicit type parameter to function result, if object + T extends { queryFnData: any; error?: infer TError; data: infer TData } + ? GetDefinedOrUndefinedQueryResult + : T extends { queryFnData: infer TQueryFnData; error?: infer TError } + ? GetDefinedOrUndefinedQueryResult + : T extends { data: infer TData; error?: infer TError } + ? GetDefinedOrUndefinedQueryResult + : // Part 2: responsible for mapping explicit type parameter to function result, if tuple + T extends [any, infer TError, infer TData] + ? GetDefinedOrUndefinedQueryResult + : T extends [infer TQueryFnData, infer TError] + ? GetDefinedOrUndefinedQueryResult + : T extends [infer TQueryFnData] + ? GetDefinedOrUndefinedQueryResult + : // Part 3: responsible for mapping inferred type to results, if no explicit parameter was provided + T extends { + queryFn?: + | QueryFunction + | SkipTokenForUseQueries + select?: Select + throwOnError?: ThrowOnError + } + ? GetDefinedOrUndefinedQueryResult< + T, + unknown extends TData ? TQueryFnData : TData, + unknown extends TError ? DefaultError : TError + > + : // Fallback + UseQueryResult + +/** + * The `queries` array accepted by `useQueries`. Recursively unwraps each tuple element so every entry's + * `queryFn`/`select`/`throwOnError` are inferred individually, up to 20 elements — past that, a tuple falls + * back to a single homogeneous options type. + * + * An opaque array (e.g. `unknown[]`) is returned as-is; a non-tuple array whose element type structurally + * matches a query options object is mapped per-element instead, still inferring each entry individually; any + * other non-tuple array — one whose element type doesn't match the expected options shape — falls back to + * that same homogeneous options type too. + * @template T - The type of the `queries` array as written at the call site. + * @template TResults - The internal accumulator that this type builds during recursion. It is not meant + * to be set explicitly. + * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not + * meant to be set explicitly. + */ +export type QueriesOptions< + T extends Array, + TResults extends Array = [], + TDepth extends ReadonlyArray = [], +> = TDepth['length'] extends MAXIMUM_DEPTH + ? Array + : T extends [] + ? [] + : T extends [infer Head] + ? [...TResults, GetUseQueryOptionsForUseQueries] + : T extends [infer Head, ...infer Tails] + ? QueriesOptions< + [...Tails], + [...TResults, GetUseQueryOptionsForUseQueries], + [...TDepth, 1] + > + : ReadonlyArray extends T + ? T + : // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogeneous type! + // use this to infer the param types in the case of Array.map() argument + T extends Array< + UseQueryOptionsForUseQueries< + infer TQueryFnData, + infer TError, + infer TData, + infer TQueryKey + > + > + ? Array< + UseQueryOptionsForUseQueries< + TQueryFnData, + TError, + TData, + TQueryKey + > + > + : // Fallback + Array + +/** + * The result type returned by `useQueries`, when no `combine` is provided. Mirrors {@link QueriesOptions}: each + * tuple element's result type is inferred individually, up to 20 elements. A non-tuple array is mapped + * per-element instead, still inferring each entry individually; only past 20 elements does this fall back to a + * single homogeneous {@link UseQueryResult} type. + * @template T - The type of the `queries` array, as inferred by {@link QueriesOptions}. + * @template TResults - The internal accumulator that this type builds during recursion. It is not meant + * to be set explicitly. + * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not + * meant to be set explicitly. + */ +export type QueriesResults< + T extends Array, + TResults extends Array = [], + TDepth extends ReadonlyArray = [], +> = TDepth['length'] extends MAXIMUM_DEPTH + ? Array + : T extends [] + ? [] + : T extends [infer Head] + ? [...TResults, GetUseQueryResult] + : T extends [infer Head, ...infer Tails] + ? QueriesResults< + [...Tails], + [...TResults, GetUseQueryResult], + [...TDepth, 1] + > + : { [K in keyof T]: GetUseQueryResult } + +type UseQueriesInput, TCombinedResult> = { + /** + * An array with query option objects, mostly identical to `useQuery` — except that `queryClient` and + * `subscribed` aren't accepted per-query (`subscribed` is a top-level option here instead), and + * `placeholderData` accepts a {@link QueriesPlaceholderDataFunction}, which is called with `previousData` + * and `previousQuery` always `undefined`, rather than `useQuery`'s placeholder function. + */ + queries: + | readonly [...QueriesOptions] + | readonly [...{ [K in keyof T]: GetUseQueryOptionsForUseQueries }] + /** + * Use this to combine the results of the queries into a single value. The result will be structurally + * shared to be as referentially stable as possible. + */ + combine?: (result: QueriesResults) => TCombinedResult + /** + * Set this to `false` to unsubscribe this observer from updates to the query cache. + * @defaultValue true + */ + subscribed?: boolean +} + +/** + * The `useQueries` hook can be used to fetch a variable number of queries. + * + * The `queries` key accepts an array with query option objects mostly identical to `useQuery` — the top-level + * `subscribed` option isn't accepted per query (see `placeholderData` below for another difference). A custom + * `QueryClient` is supplied once, as `useQueries`' own top-level second argument, rather than per query. + * + * Having the same query key more than once in the array of query objects may cause some data to be shared + * between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired + * structure. + * + * The `combine` option can be used to combine the results of the queries into a single value. The result will + * be structurally shared to be as referentially stable as possible. + * @param options - The `queries` array to run, and the optional `combine` and `subscribed` options. + * @param queryClient - Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context + * will be used. + * @returns The combined result. Without `combine`, this is an array with all the query results, in the same + * order as the input. When `combine` is provided, this is the value returned by `combine` instead. + * @throws {Error} The error of the first query that should be thrown to the nearest error boundary (see + * `throwOnError`). While suspending, it throws a promise instead. + * @remarks The `combine` function only re-runs if it changed referentially, or if any of the query results + * changed. An inlined `combine` function, as shown in the example below, therefore runs on every render — wrap + * it in `useCallback`, or extract it to a stable function reference if it doesn't have any dependencies, to + * avoid that. + * + * Unlike `useQuery`, `useQueries` cannot infer the `data` argument of an _inline_ `select` from its sibling + * `queryFn`. Because `useQueries` infers the type of the whole `queries` array at once, the `select` parameter + * of a query object written inline cannot be contextually typed from that same object's `queryFn`, so it falls + * back to `unknown` — a [known TypeScript limitation](https://github.com/TanStack/query/issues/6556). Annotate + * the `select` parameter explicitly, or define the query with {@link queryOptions}, which resolves its types in + * a single object _before_ it reaches `useQueries`, to work around this — see the example below. The same + * limitation applies to {@link useSuspenseQueries}. + * + * `placeholderData` is supported here too, but unlike `useQuery`, it doesn't receive information from + * previously rendered queries, because the number of queries can differ between renders. + * @example + * ```tsx + * import { useQueries } from '@tanstack/react-query-pluggable' + * + * function Posts({ ids }: { ids: Array }) { + * const postQueries = useQueries({ + * queries: ids.map((id) => ({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * staleTime: Infinity, + * })), + * }) + * + * return ( + *
      + * {postQueries.map((query, index) => { + * if (query.isPending) return
    • Loading...
    • + * if (query.isError) return
    • Error: {query.error.message}
    • + * return
    • {query.data.title}
    • + * })} + *
    + * ) + * } + * ``` + * @example + * Combining results into a single value: + * ```tsx + * import { useQueries } from '@tanstack/react-query-pluggable' + * + * function Posts({ ids }: { ids: Array }) { + * const { data, isPending, isError } = useQueries({ + * queries: ids.map((id) => ({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * })), + * combine: (postQueries) => { + * return { + * data: postQueries.map((query) => query.data), + * isPending: postQueries.some((query) => query.isPending), + * isError: postQueries.some((query) => query.isError), + * } + * }, + * }) + * + * if (isPending) return 'Loading...' + * if (isError) return 'Error loading posts' + * + * return ( + *
      + * {data.map((post) => ( + *
    • {post?.title}
    • + * ))} + *
    + * ) + * } + * ``` + * @example + * Typing `select` via {@link queryOptions}. Note that spreading a `queryOptions` result and overriding + * `select` inline still falls back to `unknown` — wrap the spread in `queryOptions` again so the override is + * resolved before it reaches `useQueries`: + * ```tsx + * import { queryOptions, select, useQueries } from '@tanstack/react-query-pluggable' + * + * const postOptions = (id: number) => + * queryOptions({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * }) + * + * function PostTitle({ id }: { id: number }) { + * const [{ data: broken }] = useQueries({ + * queries: [ + * { + * ...postOptions(id), + * // ❌ `data` is `unknown` here + * select: [select, (data) => data.title], + * }, + * ], + * }) + * + * const [{ data: fixed }] = useQueries({ + * queries: [ + * queryOptions({ + * ...postOptions(id), + * // ✅ `data` is `Post` + * select: [select, (data) => data.title], + * }), + * ], + * }) + * + * return

    {fixed}

    + * } + * ``` + */ +export function useQueries< + T extends Array, + TCombinedResult = QueriesResults, +>( + options: UseQueriesInput, + queryClient?: QueryClient, +): TCombinedResult { + return useBaseQueries(options, queryClient) +} + +/** + * Reads and subscribes to multiple queries. The dedicated Suspense hook can + * supply a render-time policy. + * @param options - The queries, combiner, and subscription setting. + * @param queryClient - The client to use in place of the nearest provider. + * @param suspense - The policy that prepares and reads queries during render. + * @returns The individual query results or the combined result. + * @throws {Error} The first query error configured to reach the error boundary. + */ +export function useBaseQueries< + T extends Array, + TCombinedResult = QueriesResults, +>( + { queries, ...options }: UseQueriesInput, + queryClient?: QueryClient, + suspense?: typeof suspenseQueriesPolicy, +): TCombinedResult { + const client = useQueryClient(queryClient) + const isRestoring = useIsRestoring() + const errorResetBoundary = useQueryErrorResetBoundary() + const subscribed = options.subscribed !== false + + const defaultedQueries = React.useMemo( + () => + queries.map((opts) => { + const defaultedOptions = defaultQueryOptions(client, { + ...opts, + suspense: !!suspense, + } as QueryObserverOptions) + + // Make sure the results are already in fetching state before subscribing or updating options + defaultedOptions._optimisticResults = isRestoring + ? 'isRestoring' + : subscribed + ? 'optimistic' + : undefined + + return defaultedOptions + }), + [queries, client, isRestoring, subscribed, suspense], + ) + + defaultedQueries.forEach((queryOptions) => { + suspense?.prepare(queryOptions) + const query = getQueryCache(client).get(queryOptions.queryHash) + ensurePreventErrorBoundaryRetry(queryOptions, errorResetBoundary, query) + }) + + useClearResetErrorBoundary(errorResetBoundary) + + const [observer] = React.useState( + () => + new QueriesObserver( + client, + defaultedQueries, + options as QueriesObserverOptions, + ), + ) + + const reader = observer.createResultReader( + defaultedQueries, + options as QueriesObserverOptions, + ) + suspense?.readQueries(defaultedQueries, reader, client, errorResetBoundary) + + const results = useObserverSnapshot( + observer, + reader, + !isRestoring && subscribed, + refreshQueries, + ) + + const firstErrorResult = results.find((result, index) => { + const query = defaultedQueries[index] + return ( + query && + getHasError({ + result, + errorResetBoundary, + throwOnError: query.throwOnError, + query: getQueryCache(client).get(query.queryHash), + suspense: query.suspense, + }) + ) + }) + + if (firstErrorResult) { + throw firstErrorResult.error + } + + return reader.combineResult(results) +} + +/** + * Refreshes each query after the group subscribes. + * @param observer - The observer that was subscribed. + */ +function refreshQueries(observer: Pick): void { + observer + .getObservers() + .forEach((queryObserver) => queryObserver.updateResult()) +} diff --git a/packages/react-query-pluggable/src/useQuery.ts b/packages/react-query-pluggable/src/useQuery.ts new file mode 100644 index 00000000000..fd5d5fd0292 --- /dev/null +++ b/packages/react-query-pluggable/src/useQuery.ts @@ -0,0 +1,390 @@ +'use client' + +import { QueryObserver } from './runtime/queryObserver' +import { useBaseQuery } from './useBaseQuery' +import type { + AnyDataTag, + DefaultError, + InfiniteData, + QueryKey, +} from '@tanstack/query-core' +import type { InfiniteQueryMode } from './infiniteQuery' +import type { + DefinedInitialDataOptions, + UndefinedInitialDataOptions, +} from './queryOptions' +import type { QueryClient } from './runtime/queryClient' +import type { suspenseQueryPolicy } from './suspense' +import type { SuspenseQueryOptions } from './suspenseQuery' +import type { + AnyUseInfiniteQueryOptions, + AnyUseQueryOptions, + DefinedUseInfiniteQueryResult, + DefinedUseQueryResult, + UseInfiniteQueryOptions, + UseInfiniteQueryResult, + UseQueryOptions, + UseQueryResult, + UseSuspenseInfiniteQueryResult, + UseSuspenseQueryResult, +} from './types' + +type PreparedQuery = + | (AnyUseQueryOptions & { queryKey: AnyDataTag; getNextPageParam?: never }) + | (AnyUseInfiniteQueryOptions & InfiniteQueryMode) + +type HasInitialData = T extends { + initialData: TQueryData | (() => TQueryData) +} + ? true + : false + +type PreparedQueryResult = T extends InfiniteQueryMode & + UseInfiniteQueryOptions< + infer TPage, + infer TError, + infer TData, + any, + infer TPageParam + > + ? T extends { renderPolicy: typeof suspenseQueryPolicy } + ? UseSuspenseInfiniteQueryResult + : HasInitialData> extends true + ? DefinedUseInfiniteQueryResult + : UseInfiniteQueryResult + : T extends UseQueryOptions< + infer TQueryFnData, + infer TError, + infer TData, + any + > + ? T extends { renderPolicy: typeof suspenseQueryPolicy } + ? UseSuspenseQueryResult + : HasInitialData> extends true + ? DefinedUseQueryResult + : UseQueryResult + : never + +/** + * Reads prepared regular or paginated options, including a choice between them. + * @param options - Query options prepared for the selected observer and render policy. + * @param queryClient - The client to use. Defaults to the nearest provider. + * @returns The result for the selected query, including pagination controls for infinite queries. + */ +export function useQuery( + options: T, + queryClient?: QueryClient, +): PreparedQueryResult + +/** + * Reads a query using the render policy supplied by `suspenseQuery`. + * @param options - Options returned by `suspenseQuery` for a running query. + * @param queryClient - Defaults to the nearest provider's client. + * @returns The result with defined data when the component can render. + */ +export function useQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: SuspenseQueryOptions, + queryClient?: QueryClient, +): UseSuspenseQueryResult + +/** + * This overload is selected when `initialData` is known to be defined, so the resulting `data` is typed as never + * `undefined` (unless a `select` changes `TData` to include `undefined`). At runtime, `data` is still `undefined` + * if `select` throws on its first call. + * @param options - The {@link DefinedInitialDataOptions} to use — everything you can pass to `useQuery`, with `initialData` known to be defined. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns The current query result, typed so that `status` is `success` or `error` (`status` never + * resolves to `pending` in this overload's type, since `initialData` guarantees data upfront). `status` is + * `error` if the query has an error from a fetch that failed after its retries or if `select` threw, and + * `success` otherwise. `isSuccess`/`isError` are derived booleans for convenience. + * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `fetchQuery`. + * @example + * ```tsx + * import { useQuery } from '@tanstack/react-query-pluggable' + * + * function Posts() { + * // `data` is `Post[]`, never `undefined`, thanks to `initialData` — even if a refetch fails, + * // so the list stays visible alongside the error. + * const { data, isError, error } = useQuery({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * initialData: [], + * }) + * + * return ( + *
    + * {isError ? Error: {error.message} : null} + *
      + * {data.map((post) =>
    • {post.title}
    • )} + *
    + *
    + * ) + * } + * ``` + */ +export function useQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: DefinedInitialDataOptions, + queryClient?: QueryClient, +): DefinedUseQueryResult + +/** + * This overload is selected when `initialData` is omitted, may be `undefined`, or is a function that may + * return `undefined`, so the resulting `data` can be `undefined`. + * @param options - The {@link UndefinedInitialDataOptions} to use — everything you can pass to `useQuery`. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns The current query result. `status` is `error` if the query has an error from a fetch that failed + * after its retries or if `select` threw, `success` if the query has cached data (even if `select` returns + * `undefined`) or data from `placeholderData`, and `pending` otherwise. `isPending`/`isSuccess`/`isError` + * are derived booleans for convenience. + * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `fetchQuery`. + * @example + * ```tsx + * import { useQuery } from '@tanstack/react-query-pluggable' + * + * function Posts() { + * const { status, data, error, isFetching } = useQuery({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * }) + * + * if (status === 'pending') return 'Loading...' + * if (status === 'error') return Error: {error.message} + * + * return ( + *
    + *
      + * {data.map((post) => ( + *
    • {post.title}
    • + * ))} + *
    + *
    {isFetching ? 'Background Updating...' : ' '}
    + *
    + * ) + * } + * ``` + * @example + * The same query, checking `isPending`/`isError` instead of `status` — pick whichever reads better to you: + * ```tsx + * import { useQuery } from '@tanstack/react-query-pluggable' + * + * function Posts() { + * const { isPending, isError, data, error } = useQuery({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * }) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return ( + *
      + * {data.map((post) =>
    • {post.title}
    • )} + *
    + * ) + * } + * ``` + */ +export function useQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: UndefinedInitialDataOptions, + queryClient?: QueryClient, +): UseQueryResult + +/** + * Fallback overload for options whose `initialData` presence isn't statically known — for example, an + * object typed as {@link UseQueryOptions} rather than an object literal. Prefer one of the other overloads + * when possible, since they infer whether `data` can be `undefined` from `initialData` directly. + * @param options - The {@link UseQueryOptions} to use — everything you can pass to `useQuery`. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns The current query result. `status` is `error` if the query has an error from a fetch that failed + * after its retries or if `select` threw, `success` if the query has cached data (even if `select` returns + * `undefined`) or data from `placeholderData`, and `pending` otherwise. `isPending`/`isSuccess`/`isError` + * are derived booleans for convenience. + * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `fetchQuery`. + * @example + * ```tsx + * import { useQuery } from '@tanstack/react-query-pluggable' + * + * function Posts() { + * const { status, data, error, isFetching } = useQuery({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * }) + * + * if (status === 'pending') return 'Loading...' + * if (status === 'error') return Error: {error.message} + * + * return ( + *
    + *
      + * {data.map((post) => ( + *
    • {post.title}
    • + * ))} + *
    + *
    {isFetching ? 'Background Updating...' : ' '}
    + *
    + * ) + * } + * ``` + * @example + * `select` derives whatever `data` a component needs from the cached value, without changing what's + * actually stored in the cache — the cache still holds the full `Post[]`, but `data` here is a `number`: + * ```tsx + * import { select, useQuery } from '@tanstack/react-query-pluggable' + * + * function PostCount() { + * const { data, isPending, isError, error } = useQuery({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * select: [select, (posts) => posts.length], + * }) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return {data} posts + * } + * ``` + * @example + * A dependent query, only enabled once `postId` is set — use `isLoading`, not `isPending`, so the + * loading state doesn't show while the query is disabled: + * ```tsx + * import { useQuery } from '@tanstack/react-query-pluggable' + * + * function Post({ postId }: { postId: number | undefined }) { + * const { data, isLoading, isError, error } = useQuery({ + * queryKey: ['post', postId], + * queryFn: () => fetchPost(postId!), + * enabled: postId != null, + * }) + * + * if (postId == null) return 'Select a post' + * if (isLoading) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return

    {data?.title}

    + * } + * ``` + * @example + * The same dependent query, type safe: `skipToken` disables the query without needing the + * non-null assertion above, since `queryFn` is only ever called when `postId` is defined. + * `refetch` doesn't work while `queryFn` is `skipToken` — use `enabled: false` instead if you + * need to trigger the query manually: + * ```tsx + * import { skipToken, useQuery } from '@tanstack/react-query-pluggable' + * + * function Post({ postId }: { postId: number | undefined }) { + * const { data, isLoading, isError, error } = useQuery({ + * queryKey: ['post', postId], + * queryFn: postId != null ? () => fetchPost(postId) : skipToken, + * }) + * + * if (postId == null) return 'Select a post' + * if (isLoading) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return

    {data?.title}

    + * } + * ``` + * @example + * Seeding a detail query from an already-cached list, to skip the loading state. `initialDataUpdatedAt` carries + * over the list's own fetch time, so that if you set a `staleTime`, it's measured from when the list was + * fetched rather than from now: + * ```tsx + * import { useQuery, useQueryClient, getQueryData, getQueryState } from '@tanstack/react-query-pluggable' + * + * function Post({ postId }: { postId: number }) { + * const queryClient = useQueryClient() + * + * const { data, isError, error } = useQuery({ + * queryKey: ['post', postId], + * queryFn: () => fetchPost(postId), + * initialData: () => + * getQueryData(queryClient, ['posts']) + * ?.find((post) => post.id === postId), + * initialDataUpdatedAt: () => + * getQueryState(queryClient, ['posts'])?.dataUpdatedAt, + * }) + * + * if (isError) return Error: {error.message} + * + * return

    {data?.title}

    + * } + * ``` + * @example + * Paginated data, keeping the previous page's data visible while the next page loads: + * ```tsx + * import { keepPreviousData, placeholderData, useQuery } from '@tanstack/react-query-pluggable' + * import { useState } from 'react' + * + * function Posts() { + * const [page, setPage] = useState(0) + * + * const { data, isPlaceholderData, isError, error } = useQuery({ + * queryKey: ['posts', page], + * queryFn: () => fetchPosts(page), + * placeholderData: placeholderData(keepPreviousData), + * }) + * + * if (isError) return Error: {error.message} + * + * return ( + *
    + *
      + * {data?.map((post) =>
    • {post.title}
    • )} + *
    + * + *
    + * ) + * } + * ``` + */ +export function useQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: UseQueryOptions, + queryClient?: QueryClient, +): UseQueryResult + +export function useQuery( + options: + | ((AnyUseQueryOptions | AnyUseInfiniteQueryOptions) & { + Observer?: InfiniteQueryMode['Observer'] + renderPolicy?: typeof suspenseQueryPolicy + }) + | null + | undefined, + queryClient?: QueryClient, +) { + return useBaseQuery( + options as AnyUseQueryOptions, + (options?.Observer ?? QueryObserver) as typeof QueryObserver, + queryClient, + options?.renderPolicy, + ) +} diff --git a/packages/react-query-pluggable/src/useSuspenseInfiniteQuery.ts b/packages/react-query-pluggable/src/useSuspenseInfiniteQuery.ts new file mode 100644 index 00000000000..7f147a14e05 --- /dev/null +++ b/packages/react-query-pluggable/src/useSuspenseInfiniteQuery.ts @@ -0,0 +1,162 @@ +'use client' + +import { infiniteQuery } from './infiniteQuery' +import { suspenseQuery } from './suspenseQuery' +import { useQuery } from './useQuery' +import type { + DefaultError, + InfiniteData, + OmitKeyof, + QueryKey, +} from '@tanstack/query-core' +import type { QueryClient } from './runtime/queryClient' +import type { + AnyUseInfiniteQueryOptions, + UseInfiniteQueryOptions, + UseInfiniteQueryResult, + UseSuspenseInfiniteQueryOptions, + UseSuspenseInfiniteQueryResult, +} from './types' + +type SkippableSuspenseInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey extends QueryKey, + TPageParam, +> = OmitKeyof< + UseInfiniteQueryOptions, + 'enabled' | 'throwOnError' +> + +/** + * The options for `useSuspenseInfiniteQuery` are the same as for `useInfiniteQuery`, except for `throwOnError` + * and `enabled`. + * + * Caveat: cancellation does not work. + * @param options - The {@link UseSuspenseInfiniteQueryOptions} to use — the same options as `useInfiniteQuery`, minus the ones listed above. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns The same object as `useInfiniteQuery`, except that `data` is guaranteed to be defined, + * `isPlaceholderData` is missing, and `status` is either `success` or `error` (with the derived flags set + * accordingly). + * @remarks Multiple suspenseful query calls in the same component suspend serially, causing a request + * waterfall — each one blocks rendering until it resolves, so the next doesn't even start fetching until + * then. There's no way to parallelize multiple infinite queries under Suspense. Also keep in mind that + * imperative fetch calls, such as `fetchNextPage`, may interfere with the default refetch behavior, + * resulting in outdated data. Make sure to call these functions only in response to user actions, or add + * conditions like `hasNextPage && !isFetching`. + * @see {@link useInfiniteQuery} for the non-Suspense version of this hook. + * @example + * The query error is thrown if a fetch fails and no cached data exists yet, so an error boundary is + * required around ``. A failed background refetch instead continues to render the cached data. + * Use {@link QueryErrorResetBoundary} to let the user retry after such an error: + * ```tsx + * import { Suspense } from 'react' + * import { ErrorBoundary } from 'react-error-boundary' + * import { + * QueryErrorResetBoundary, + * useSuspenseInfiniteQuery, + * } from '@tanstack/react-query-pluggable' + * + * function Projects() { + * // `data` is guaranteed to be defined here — no `isPending` check needed. + * const { data, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage } = + * useSuspenseInfiniteQuery({ + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * return ( + *
    + *
      + * {data.pages.map((page) => + * page.projects.map((project) =>
    • {project.name}
    • ), + * )} + *
    + * + *
    + * ) + * } + * + * function App() { + * return ( + * + * {({ reset }) => ( + * ( + *
    + * There was an error! + * + *
    + * )} + * > + * Loading projects...}> + * + * + *
    + * )} + *
    + * ) + * } + * ``` + */ +export function useSuspenseInfiniteQuery< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + options: UseSuspenseInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + queryClient?: QueryClient, +): UseSuspenseInfiniteQueryResult + +/** + * A skipped query does not fetch automatically or suspend. Query errors without cached + * data reach the nearest error boundary. + * @param options - The infinite query options. The query function can be `skipToken`. + * @param queryClient - The client to use. Defaults to the client from the nearest context. + * @returns An infinite query result that can be pending and can have undefined data. + */ +export function useSuspenseInfiniteQuery< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + options: SkippableSuspenseInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + queryClient?: QueryClient, +): UseInfiniteQueryResult + +export function useSuspenseInfiniteQuery( + options: AnyUseInfiniteQueryOptions, + queryClient?: QueryClient, +) { + return useQuery(suspenseQuery(infiniteQuery(options)), queryClient) +} diff --git a/packages/react-query-pluggable/src/useSuspenseQueries.ts b/packages/react-query-pluggable/src/useSuspenseQueries.ts new file mode 100644 index 00000000000..6061b40950b --- /dev/null +++ b/packages/react-query-pluggable/src/useSuspenseQueries.ts @@ -0,0 +1,553 @@ +'use client' + +import { skipToken } from '@tanstack/query-core/primitives' +import { defaultThrowOnError, suspenseQueriesPolicy } from './suspense' +import { useBaseQueries } from './useQueries' +import type { + DefaultError, + OmitKeyof, + QueriesPlaceholderDataFunction, + QueryKey, +} from '@tanstack/query-core' +import type { placeholderData } from './runtime/placeholderData' +import type { Select } from './runtime/projectionTypes' +import type { QueryClient } from './runtime/queryClient' +import type { QueryFunction, ThrowOnError } from './runtime/types' +import type { UseSuspenseQueryOptions, UseSuspenseQueryResult } from './types' + +// `placeholderData` functions in useQueries never receive previous query data. +type UseSuspenseQueryOptionsForUseSuspenseQueries< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = OmitKeyof< + UseSuspenseQueryOptions, + 'placeholderData' +> & { + placeholderData?: readonly [ + typeof placeholderData, + TQueryFnData | QueriesPlaceholderDataFunction, + ] +} + +// Avoid TS depth-limit error in case of large array literal +type MAXIMUM_DEPTH = 20 + +// Widen the type of the symbol to enable type inference even if skipToken is not immutable. +type SkipTokenForUseQueries = symbol + +type GetUseSuspenseQueryOptions = + // Part 1: responsible for applying explicit type parameter to function arguments, if object { queryFnData: TQueryFnData, error: TError, data: TData } + T extends { + queryFnData: infer TQueryFnData + error?: infer TError + data: infer TData + } + ? UseSuspenseQueryOptionsForUseSuspenseQueries + : T extends { queryFnData: infer TQueryFnData; error?: infer TError } + ? UseSuspenseQueryOptionsForUseSuspenseQueries + : T extends { data: infer TData; error?: infer TError } + ? UseSuspenseQueryOptionsForUseSuspenseQueries + : // Part 2: responsible for applying explicit type parameter to function arguments, if tuple [TQueryFnData, TError, TData] + T extends [infer TQueryFnData, infer TError, infer TData] + ? UseSuspenseQueryOptionsForUseSuspenseQueries< + TQueryFnData, + TError, + TData + > + : T extends [infer TQueryFnData, infer TError] + ? UseSuspenseQueryOptionsForUseSuspenseQueries + : T extends [infer TQueryFnData] + ? UseSuspenseQueryOptionsForUseSuspenseQueries + : // Part 3: responsible for inferring and enforcing type if no explicit parameter was provided + T extends { + queryFn?: + | QueryFunction + | SkipTokenForUseQueries + select?: Select + throwOnError?: ThrowOnError + } + ? UseSuspenseQueryOptionsForUseSuspenseQueries< + TQueryFnData, + TError, + TData, + TQueryKey + > + : T extends { + queryFn?: + | QueryFunction + | SkipTokenForUseQueries + throwOnError?: ThrowOnError + } + ? UseSuspenseQueryOptionsForUseSuspenseQueries< + TQueryFnData, + TError, + TQueryFnData, + TQueryKey + > + : // Fallback + UseSuspenseQueryOptionsForUseSuspenseQueries + +type GetUseSuspenseQueryResult = + // Part 1: responsible for mapping explicit type parameter to function result, if object + T extends { queryFnData: any; error?: infer TError; data: infer TData } + ? UseSuspenseQueryResult + : T extends { queryFnData: infer TQueryFnData; error?: infer TError } + ? UseSuspenseQueryResult + : T extends { data: infer TData; error?: infer TError } + ? UseSuspenseQueryResult + : // Part 2: responsible for mapping explicit type parameter to function result, if tuple + T extends [any, infer TError, infer TData] + ? UseSuspenseQueryResult + : T extends [infer TQueryFnData, infer TError] + ? UseSuspenseQueryResult + : T extends [infer TQueryFnData] + ? UseSuspenseQueryResult + : // Part 3: responsible for mapping inferred type to results, if no explicit parameter was provided + T extends { + queryFn?: + | QueryFunction + | SkipTokenForUseQueries + select?: Select + throwOnError?: ThrowOnError + } + ? UseSuspenseQueryResult< + unknown extends TData ? TQueryFnData : TData, + unknown extends TError ? DefaultError : TError + > + : T extends { + queryFn?: + | QueryFunction + | SkipTokenForUseQueries + throwOnError?: ThrowOnError + } + ? UseSuspenseQueryResult< + TQueryFnData, + unknown extends TError ? DefaultError : TError + > + : // Fallback + UseSuspenseQueryResult + +/** + * The `queries` array accepted by `useSuspenseQueries`. Recursively unwraps each tuple element so every + * entry's `queryFn`/`select` are inferred individually, up to 20 elements — past that, a tuple falls back to + * a single homogeneous {@link UseSuspenseQueryOptions} type. + * + * An opaque array (e.g. `unknown[]`) is returned as-is; a non-tuple array whose element type structurally + * matches a query options object is mapped per-element instead, still inferring each entry individually; any + * other non-tuple array — one whose element type doesn't match the expected options shape — falls back to + * that same homogeneous options type too. + * @template T - The type of the `queries` array as written at the call site. + * @template TResults - The internal accumulator that this type builds during recursion. It is not meant + * to be set explicitly. + * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not + * meant to be set explicitly. + */ +export type SuspenseQueriesOptions< + T extends Array, + TResults extends Array = [], + TDepth extends ReadonlyArray = [], +> = TDepth['length'] extends MAXIMUM_DEPTH + ? Array + : T extends [] + ? [] + : T extends [infer Head] + ? [...TResults, GetUseSuspenseQueryOptions] + : T extends [infer Head, ...infer Tails] + ? SuspenseQueriesOptions< + [...Tails], + [...TResults, GetUseSuspenseQueryOptions], + [...TDepth, 1] + > + : Array extends T + ? T + : // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogeneous type! + // use this to infer the param types in the case of Array.map() argument + T extends Array< + UseSuspenseQueryOptionsForUseSuspenseQueries< + infer TQueryFnData, + infer TError, + infer TData, + infer TQueryKey + > + > + ? Array< + UseSuspenseQueryOptionsForUseSuspenseQueries< + TQueryFnData, + TError, + TData, + TQueryKey + > + > + : // Fallback + Array + +/** + * The result type returned by `useSuspenseQueries`, when no `combine` is provided. Mirrors + * {@link SuspenseQueriesOptions}: each tuple element's result type is inferred individually, up to 20 elements. + * A non-tuple array is mapped per-element instead, still inferring each entry individually; only past 20 + * elements does this fall back to a single homogeneous {@link UseSuspenseQueryResult} type. + * @template T - The type of the `queries` array, as inferred by {@link SuspenseQueriesOptions}. + * @template TResults - The internal accumulator that this type builds during recursion. It is not meant + * to be set explicitly. + * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not + * meant to be set explicitly. + */ +export type SuspenseQueriesResults< + T extends Array, + TResults extends Array = [], + TDepth extends ReadonlyArray = [], +> = TDepth['length'] extends MAXIMUM_DEPTH + ? Array + : T extends [] + ? [] + : T extends [infer Head] + ? [...TResults, GetUseSuspenseQueryResult] + : T extends [infer Head, ...infer Tails] + ? SuspenseQueriesResults< + [...Tails], + [...TResults, GetUseSuspenseQueryResult], + [...TDepth, 1] + > + : { [K in keyof T]: GetUseSuspenseQueryResult } + +/** + * The options for `useSuspenseQueries` are the same as for `useQueries`, except that the top-level `subscribed` + * option isn't supported, and each `query` can't have `throwOnError`, `enabled`, or `placeholderData`. + * @param options - The `queries` array to run in Suspense, and an optional `combine` function. + * @param queryClient - Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context + * will be used. + * @returns The same structure as `useQueries`, except that for each `query`, `data` is guaranteed to be + * defined, `isPlaceholderData` is missing, and `status` is either `success` or `error` (with the derived + * flags set accordingly). + * + * Caveat: the component will only re-mount after all queries have finished loading. Hence, if a query has gone + * stale in the time it took for all the queries to complete, it will be fetched again at re-mount. To avoid + * this, make sure to set a high enough `staleTime`. Cancellation does not work. + * @example + * The query error is thrown if a fetch fails and no cached data exists yet, so an error boundary is + * required around ``. A failed background refetch instead continues to render the cached data. + * Use {@link QueryErrorResetBoundary} to let the user retry after such an error: + * ```tsx + * import { Suspense } from 'react' + * import { ErrorBoundary } from 'react-error-boundary' + * import { + * QueryErrorResetBoundary, + * useSuspenseQueries, + * } from '@tanstack/react-query-pluggable' + * + * function Posts({ ids }: { ids: Array }) { + * // Every result is guaranteed to be defined — no per-query `isPending` check needed. + * const postQueries = useSuspenseQueries({ + * queries: ids.map((id) => ({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * })), + * }) + * + * return ( + *
      + * {postQueries.map((query) => ( + *
    • {query.data.title}
    • + * ))} + *
    + * ) + * } + * + * function App() { + * return ( + * + * {({ reset }) => ( + * ( + *
    + * There was an error! + * + *
    + * )} + * > + * Loading posts...}> + * + * + *
    + * )} + *
    + * ) + * } + * ``` + * @example + * Several different queries — use `useSuspenseQueries` instead of multiple `useSuspenseQuery` calls, so + * they fetch in parallel rather than suspending one after another: + * ```tsx + * import { Suspense } from 'react' + * import { ErrorBoundary } from 'react-error-boundary' + * import { + * QueryErrorResetBoundary, + * useSuspenseQueries, + * } from '@tanstack/react-query-pluggable' + * + * function Dashboard() { + * const [usersQuery, teamsQuery, projectsQuery] = useSuspenseQueries({ + * queries: [ + * { queryKey: ['users'], queryFn: fetchUsers }, + * { queryKey: ['teams'], queryFn: fetchTeams }, + * { queryKey: ['projects'], queryFn: fetchProjects }, + * ], + * }) + * + * return ( + *
    + * + * + * + *
    + * ) + * } + * + * function App() { + * return ( + * + * {({ reset }) => ( + * ( + *
    + * There was an error! + * + *
    + * )} + * > + * Loading dashboard...}> + * + * + *
    + * )} + *
    + * ) + * } + * ``` + * @example + * `combine`s the results into a single boolean, so `Refresh` only re-renders when that boolean changes, + * not on every individual query update. This overload is the only one that accepts `combine`: + * ```tsx + * import { Suspense } from 'react' + * import { ErrorBoundary } from 'react-error-boundary' + * import { + * QueryErrorResetBoundary, + * useSuspenseQueries, + * } from '@tanstack/react-query-pluggable' + * + * function Refresh() { + * const anyFetching = useSuspenseQueries({ + * queries: [ + * { queryKey: ['users'], queryFn: fetchUsers }, + * { queryKey: ['teams'], queryFn: fetchTeams }, + * ], + * combine: (results) => results.some((result) => result.isFetching), + * }) + * + * return anyFetching ? Refreshing… : null + * } + * + * function App() { + * return ( + * + * {({ reset }) => ( + * ( + *
    + * There was an error! + * + *
    + * )} + * > + * Loading dashboard...}> + * + * + *
    + * )} + *
    + * ) + * } + * ``` + */ +export function useSuspenseQueries< + T extends Array, + TCombinedResult = SuspenseQueriesResults, +>( + options: { + /** + * An array with query option objects identical to `useSuspenseQuery`. + */ + queries: + | readonly [...SuspenseQueriesOptions] + | readonly [...{ [K in keyof T]: GetUseSuspenseQueryOptions }] + /** + * Use this to combine the results of the queries into a single value. The result will be structurally + * shared to be as referentially stable as possible. + */ + combine?: (result: SuspenseQueriesResults) => TCombinedResult + }, + queryClient?: QueryClient, +): TCombinedResult + +/** + * The options for `useSuspenseQueries` are the same as for `useQueries`, except that the top-level `subscribed` + * option isn't supported, and each `query` can't have `throwOnError`, `enabled`, or `placeholderData`. + * @param options - The `queries` array to run in Suspense, and an optional `combine` function. + * @param queryClient - Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context + * will be used. + * @returns The same structure as `useQueries`, except that for each `query`, `data` is guaranteed to be + * defined, `isPlaceholderData` is missing, and `status` is either `success` or `error` (with the derived + * flags set accordingly). + * + * Caveat: the component will only re-mount after all queries have finished loading. Hence, if a query has gone + * stale in the time it took for all the queries to complete, it will be fetched again at re-mount. To avoid + * this, make sure to set a high enough `staleTime`. Cancellation does not work. + * @example + * The query error is thrown if a fetch fails and no cached data exists yet, so an error boundary is + * required around ``. A failed background refetch instead continues to render the cached data. + * Use {@link QueryErrorResetBoundary} to let the user retry after such an error: + * ```tsx + * import { Suspense } from 'react' + * import { ErrorBoundary } from 'react-error-boundary' + * import { + * QueryErrorResetBoundary, + * useSuspenseQueries, + * } from '@tanstack/react-query-pluggable' + * + * function Posts({ ids }: { ids: Array }) { + * // Every result is guaranteed to be defined — no per-query `isPending` check needed. + * const postQueries = useSuspenseQueries({ + * queries: ids.map((id) => ({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * })), + * }) + * + * return ( + *
      + * {postQueries.map((query) => ( + *
    • {query.data.title}
    • + * ))} + *
    + * ) + * } + * + * function App() { + * return ( + * + * {({ reset }) => ( + * ( + *
    + * There was an error! + * + *
    + * )} + * > + * Loading posts...}> + * + * + *
    + * )} + *
    + * ) + * } + * ``` + * @example + * Several different queries — use `useSuspenseQueries` instead of multiple `useSuspenseQuery` calls, so + * they fetch in parallel rather than suspending one after another: + * ```tsx + * import { Suspense } from 'react' + * import { ErrorBoundary } from 'react-error-boundary' + * import { + * QueryErrorResetBoundary, + * useSuspenseQueries, + * } from '@tanstack/react-query-pluggable' + * + * function Dashboard() { + * const [usersQuery, teamsQuery, projectsQuery] = useSuspenseQueries({ + * queries: [ + * { queryKey: ['users'], queryFn: fetchUsers }, + * { queryKey: ['teams'], queryFn: fetchTeams }, + * { queryKey: ['projects'], queryFn: fetchProjects }, + * ], + * }) + * + * return ( + *
    + * + * + * + *
    + * ) + * } + * + * function App() { + * return ( + * + * {({ reset }) => ( + * ( + *
    + * There was an error! + * + *
    + * )} + * > + * Loading dashboard...}> + * + * + *
    + * )} + *
    + * ) + * } + * ``` + */ +export function useSuspenseQueries< + T extends Array, + TCombinedResult = SuspenseQueriesResults, +>( + options: { + /** + * An array with query option objects identical to `useSuspenseQuery`. + */ + queries: readonly [...SuspenseQueriesOptions] + /** + * Use this to combine the results of the queries into a single value. The result will be structurally + * shared to be as referentially stable as possible. + */ + combine?: (result: SuspenseQueriesResults) => TCombinedResult + }, + queryClient?: QueryClient, +): TCombinedResult + +export function useSuspenseQueries(options: any, queryClient?: QueryClient) { + return useBaseQueries( + { + ...options, + queries: options.queries.map((query: any) => { + if (process.env.NODE_ENV !== 'production') { + if (query.queryFn === skipToken) { + console.error('skipToken is not allowed for useSuspenseQueries') + } + } + + return { + ...query, + throwOnError: defaultThrowOnError, + enabled: true, + } + }), + }, + queryClient, + suspenseQueriesPolicy, + ) +} diff --git a/packages/react-query-pluggable/src/useSuspenseQuery.ts b/packages/react-query-pluggable/src/useSuspenseQuery.ts new file mode 100644 index 00000000000..3550ca21aa3 --- /dev/null +++ b/packages/react-query-pluggable/src/useSuspenseQuery.ts @@ -0,0 +1,136 @@ +'use client' + +import { suspenseQuery } from './suspenseQuery' +import { useQuery } from './useQuery' +import type { DefaultError, OmitKeyof, QueryKey } from '@tanstack/query-core' +import type { QueryClient } from './runtime/queryClient' +import type { + UseQueryOptions, + UseQueryResult, + UseSuspenseQueryOptions, + UseSuspenseQueryResult, +} from './types' + +/** Options for a Suspense reader whose query function can be skipped. */ +export type SkippableSuspenseQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey extends QueryKey, +> = OmitKeyof< + UseQueryOptions, + 'enabled' | 'throwOnError' +> + +/** + * Runs a query with Suspense. The options match those of `useQuery` except for `throwOnError` and `enabled`. + * + * Caveat: cancellation does not work. + * @param options - The {@link UseSuspenseQueryOptions} for a query that always runs. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns A result with data of type `TData` and a status of `success` or `error`. + * @remarks Multiple `useSuspenseQuery` calls in the same component suspend serially, causing a request + * waterfall — each one blocks rendering until it resolves, so the next doesn't even start fetching until then. + * Use {@link useSuspenseQueries} instead when you have more than one suspenseful query in a component, so they + * fetch in parallel. + * @example + * The query error is thrown if the fetch fails and no cached data exists yet, so an error boundary is + * required around ``. A failed background refetch instead continues to render the cached data. + * Use {@link QueryErrorResetBoundary} to let the user retry after such an error: + * ```tsx + * import { Suspense } from 'react' + * import { ErrorBoundary } from 'react-error-boundary' + * import { QueryErrorResetBoundary, useSuspenseQuery } from '@tanstack/react-query-pluggable' + * + * function Posts() { + * // `data` is guaranteed to be defined here — no `isPending` check needed. + * const { data, isFetching } = useSuspenseQuery({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * }) + * + * return ( + *
    + *

    Posts {isFetching ? '(refreshing...)' : null}

    + *
      + * {data.map((post) => ( + *
    • {post.title}
    • + * ))} + *
    + *
    + * ) + * } + * + * function App() { + * return ( + * + * {({ reset }) => ( + * ( + *
    + * There was an error! + * + *
    + * )} + * > + * Loading posts...}> + * + * + *
    + * )} + *
    + * ) + * } + * ``` + */ +export function useSuspenseQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: UseSuspenseQueryOptions, + queryClient?: QueryClient, +): UseSuspenseQueryResult + +/** + * Pass `skipToken` as `queryFn` to skip the query. While skipped, the query can read cached data + * but does not fetch automatically or suspend. Query errors without cached data reach the nearest error boundary. + * Pass a query function to resume normal Suspense behavior. + * @param options - Options for a query that can be skipped. + * @param queryClient - The client to use. Defaults to the client from the nearest context. + * @returns A result whose data can be undefined and whose status can be `pending`. + */ +export function useSuspenseQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: SkippableSuspenseQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey + >, + queryClient?: QueryClient, +): UseQueryResult + +export function useSuspenseQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: SkippableSuspenseQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey + >, + queryClient?: QueryClient, +): UseQueryResult { + return useQuery(suspenseQuery(options), queryClient) +} diff --git a/packages/react-query-pluggable/tests/compat-polling.ts b/packages/react-query-pluggable/tests/compat-polling.ts new file mode 100644 index 00000000000..458bc830135 --- /dev/null +++ b/packages/react-query-pluggable/tests/compat-polling.ts @@ -0,0 +1,6 @@ +export { refetchInterval } from '../src' + +export type IntervalInput = Extract< + TOption, + { value: unknown } +>['value'] diff --git a/packages/react-query-pluggable/tests/compat-projection.ts b/packages/react-query-pluggable/tests/compat-projection.ts new file mode 100644 index 00000000000..c8c3b4c7de7 --- /dev/null +++ b/packages/react-query-pluggable/tests/compat-projection.ts @@ -0,0 +1,42 @@ +import { placeholderData, select } from '../src' + +export { select, placeholderData } +export const selectOption = 'select' +export const placeholderOption = 'placeholderData' +export type ProjectionInput = T extends readonly [unknown, infer Input] + ? Input + : T + +/** Returns the input supplied to a projection feature. */ +export function projectionInput( + option: readonly [unknown, T] | undefined, +): T | undefined { + return option?.[1] +} + +/** Preserves a shared test's optional callback when migrating a stored reference. */ +export function portSelect( + input: T, +): T extends undefined ? undefined : readonly [typeof select, T] { + return ( + input === undefined ? undefined : [select, input] + ) as T extends undefined ? undefined : readonly [typeof select, T] +} + +/** Preserves a shared test's optional placeholder when migrating a stored reference. */ +export function portPlaceholder( + input: T, +): T extends undefined ? undefined : readonly [typeof placeholderData, T] { + return ( + input === undefined ? undefined : [placeholderData, input] + ) as T extends undefined ? undefined : readonly [typeof placeholderData, T] +} + +/** A stored pluggable selection option for a shared React test. */ +export type SelectSetting = readonly [typeof select, TValue] + +/** A stored pluggable placeholder option for a shared React test. */ +export type PlaceholderSetting = readonly [ + typeof placeholderData, + TValue, +] diff --git a/packages/react-query-pluggable/tests/compat-scope.ts b/packages/react-query-pluggable/tests/compat-scope.ts new file mode 100644 index 00000000000..7dc29d882ba --- /dev/null +++ b/packages/react-query-pluggable/tests/compat-scope.ts @@ -0,0 +1 @@ +export { serialScope } from '../src/runtime/serialScope' diff --git a/packages/react-query-pluggable/tsconfig.json b/packages/react-query-pluggable/tsconfig.json new file mode 100644 index 00000000000..58e959cbe0f --- /dev/null +++ b/packages/react-query-pluggable/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "outDir": "./dist-ts", + "rootDir": ".", + "jsx": "react-jsx" + }, + "include": ["src", "tests", "*.config.ts", "*.config.js", "package.json"] +} diff --git a/packages/react-query-pluggable/tsconfig.legacy.json b/packages/react-query-pluggable/tsconfig.legacy.json new file mode 100644 index 00000000000..20f2156d95b --- /dev/null +++ b/packages/react-query-pluggable/tsconfig.legacy.json @@ -0,0 +1,9 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "outDir": "./dist-ts/legacy" + }, + "include": ["src"], + "exclude": ["src/__tests__"] +} diff --git a/packages/react-query-pluggable/tsconfig.prod.json b/packages/react-query-pluggable/tsconfig.prod.json new file mode 100644 index 00000000000..2bb29fdf02a --- /dev/null +++ b/packages/react-query-pluggable/tsconfig.prod.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "incremental": false, + "composite": false, + "rootDir": "../../" + }, + "include": ["src"], + "exclude": ["src/__tests__"] +} diff --git a/packages/react-query-pluggable/tsdown.config.ts b/packages/react-query-pluggable/tsdown.config.ts new file mode 100644 index 00000000000..a486c9a8d14 --- /dev/null +++ b/packages/react-query-pluggable/tsdown.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from 'tsdown' +import { getTsdownConfig } from './root.tsdown.config.js' + +export default defineConfig({ + ...getTsdownConfig({ entry: ['src/index.ts'] }), + // Preserve React's client boundaries and let the consuming app remove unused plugins. + unbundle: true, +}) diff --git a/packages/react-query/src/__tests__/infiniteQueryOptions.test-d.tsx b/packages/react-query/src/__tests__/infiniteQueryOptions.test-d.tsx index b9e0ccc680f..8310469c993 100644 --- a/packages/react-query/src/__tests__/infiniteQueryOptions.test-d.tsx +++ b/packages/react-query/src/__tests__/infiniteQueryOptions.test-d.tsx @@ -1,5 +1,6 @@ import { QueryClient, dataTagSymbol, skipToken } from '@tanstack/query-core' import { createKey } from '@tanstack/query-test-utils' +import { selectOption } from '@tanstack/query-test-utils/projection' import { assertType, describe, expectTypeOf, it } from 'vitest' import { defaultQueryFn } from '..' import { infiniteQueryOptions } from '../infiniteQueryOptions' @@ -43,7 +44,7 @@ describe('infiniteQueryOptions', () => { staleTime: 1000, getNextPageParam: () => 1, initialPageParam: 1, - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toEqualTypeOf>() }, }) @@ -71,7 +72,7 @@ describe('infiniteQueryOptions', () => { queryFn: () => Promise.resolve('string'), getNextPageParam: () => 1, initialPageParam: 1, - select: (data) => data.pages, + [selectOption]: (data) => data.pages, }) const { data } = useInfiniteQuery(options) @@ -99,7 +100,7 @@ describe('infiniteQueryOptions', () => { queryFn: () => Promise.resolve('string'), getNextPageParam: () => 1, initialPageParam: 1, - select: (data) => data.pages, + [selectOption]: (data) => data.pages, }) const { data } = useSuspenseInfiniteQuery(options) @@ -126,7 +127,7 @@ describe('infiniteQueryOptions', () => { queryFn: () => Promise.resolve('string'), getNextPageParam: () => 1, initialPageParam: 1, - select: (data) => data.pages, + [selectOption]: (data) => data.pages, }) const data = await new QueryClient().infiniteQuery(options) @@ -189,7 +190,7 @@ describe('infiniteQueryOptions', () => { const { queryKey: tagged } = infiniteQueryOptions({ queryKey: createKey(), queryFn: () => Promise.resolve('string'), - select: (data) => data.pages, + [selectOption]: (data) => data.pages, getNextPageParam: () => 1, initialPageParam: 1, }) diff --git a/packages/react-query/src/__tests__/placeholderData.test.ts b/packages/react-query/src/__tests__/placeholderData.test.ts index 17b5e7a4d89..9dbdae7eb21 100644 --- a/packages/react-query/src/__tests__/placeholderData.test.ts +++ b/packages/react-query/src/__tests__/placeholderData.test.ts @@ -1,7 +1,15 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { + placeholderOption, + selectOption, +} from '@tanstack/query-test-utils/projection' import { renderHook } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { QueryClient, useQueries, useQuery } from '..' +import type { + PlaceholderSetting, + SelectSetting, +} from '@tanstack/query-test-utils/projection' class Placeholder { constructor(readonly value: number) {} @@ -10,8 +18,8 @@ class Placeholder { type Options = { queryKey: ReadonlyArray queryFn: () => Promise - placeholderData: Placeholder - select?: (data: Placeholder) => Placeholder | Set + placeholderData: PlaceholderSetting + select?: SelectSetting<(data: Placeholder) => Placeholder | Set> } function useMultiple(options: Options, client: QueryClient) { @@ -78,8 +86,8 @@ describe('placeholder updates', () => { { queryKey: key, queryFn: () => new Promise(() => {}), - placeholderData: input, - select, + [placeholderOption]: input, + [selectOption]: select, }, client, ) @@ -108,7 +116,16 @@ describe('placeholder updates', () => { const queryFn = () => sleep(10).then(() => ({ value: 1 })) const { result, rerender } = renderHook(() => { const [{ data, error }] = useQueries( - { queries: [{ queryKey, queryFn, placeholderData, select }] }, + { + queries: [ + { + queryKey, + queryFn, + [placeholderOption]: placeholderData, + [selectOption]: select, + }, + ], + }, client, ) return { data, error } diff --git a/packages/react-query/src/__tests__/queryOptions.test-d.tsx b/packages/react-query/src/__tests__/queryOptions.test-d.tsx index b48d2dd7259..7eadbb77a48 100644 --- a/packages/react-query/src/__tests__/queryOptions.test-d.tsx +++ b/packages/react-query/src/__tests__/queryOptions.test-d.tsx @@ -1,5 +1,6 @@ import { QueryClient, dataTagSymbol, skipToken } from '@tanstack/query-core' import { createKey } from '@tanstack/query-test-utils' +import { selectOption } from '@tanstack/query-test-utils/projection' import { assertType, describe, expectTypeOf, it } from 'vitest' import { defaultQueryFn } from '..' import { queryOptions } from '../queryOptions' @@ -38,7 +39,7 @@ describe('queryOptions', () => { queryKey: createKey(), queryFn: () => Promise.resolve(5), staleTime: 1000, - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toEqualTypeOf() }, }) @@ -78,7 +79,7 @@ describe('queryOptions', () => { const options = queryOptions({ queryKey: ['key'], queryFn: () => Promise.resolve(5), - select: (data) => data.toString(), + [selectOption]: (data) => data.toString(), }) const data = await new QueryClient().query(options) @@ -100,7 +101,7 @@ describe('queryOptions', () => { const options = queryOptions({ queryKey: ['key'], queryFn: Math.random() > 0.5 ? skipToken : () => Promise.resolve(5), - select: (data) => data.toFixed(), + [selectOption]: (data) => data.toFixed(), }) const data = await new QueryClient().query(options) @@ -151,7 +152,7 @@ describe('queryOptions', () => { const { queryKey: tagged } = queryOptions({ queryKey: createKey(), queryFn: () => Promise.resolve(5), - select: (data) => data.toString(), + [selectOption]: (data) => data.toString(), }) expectTypeOf(tagged[dataTagSymbol]).toEqualTypeOf() diff --git a/packages/react-query/src/__tests__/transition.test.tsx b/packages/react-query/src/__tests__/transition.test.tsx index b541cdd03c7..cf561c3d2af 100644 --- a/packages/react-query/src/__tests__/transition.test.tsx +++ b/packages/react-query/src/__tests__/transition.test.tsx @@ -1,4 +1,8 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { + placeholderOption, + selectOption, +} from '@tanstack/query-test-utils/projection' import { act, fireEvent } from '@testing-library/react' import * as React from 'react' import { startTransition, useDeferredValue } from 'react' @@ -33,7 +37,7 @@ describe('react transitions', () => { queryKey: [key, id], queryFn: () => Promise.resolve({ value: id }), staleTime: Infinity, - select, + [selectOption]: select, }) if (id === 2) { renderB(data) @@ -167,7 +171,7 @@ describe('react transitions', () => { const query = useSuspenseQuery({ queryKey: [key, queryCount], queryFn: () => queryFn(queryCount), - placeholderData: + [placeholderOption]: placeholderMode === 'static' ? 'placeholder' : keepPreviousData, }) @@ -242,7 +246,7 @@ describe('react transitions', () => { const query = useSuspenseQuery({ queryKey: [...key, 'placeholder', count], queryFn: () => placeholderQueryFn(count), - placeholderData: + [placeholderOption]: placeholderMode === 'static' ? 'placeholder' : keepPreviousData, }) return
    {query.data}
    @@ -324,7 +328,7 @@ describe('react transitions', () => { const placeholderQuery = useSuspenseQuery({ queryKey: [...key, 'placeholder', count], queryFn: () => placeholderQueryFn(count), - placeholderData: keepPreviousData, + [placeholderOption]: keepPreviousData, }) const suspenseQuery = useSuspenseQuery({ queryKey: [...key, 'suspense', count], diff --git a/packages/react-query/src/__tests__/useInfiniteQuery.test-d.tsx b/packages/react-query/src/__tests__/useInfiniteQuery.test-d.tsx index 82eaaaf3a0e..6f8aa0673e4 100644 --- a/packages/react-query/src/__tests__/useInfiniteQuery.test-d.tsx +++ b/packages/react-query/src/__tests__/useInfiniteQuery.test-d.tsx @@ -1,5 +1,6 @@ import { QueryClient } from '@tanstack/query-core' import { createKey } from '@tanstack/query-test-utils' +import { selectOption } from '@tanstack/query-test-utils/projection' import { describe, expectTypeOf, it } from 'vitest' import { useInfiniteQuery } from '../useInfiniteQuery' import type { InfiniteData } from '@tanstack/query-core' @@ -56,7 +57,7 @@ describe('select', () => { }, initialPageParam: 1, getNextPageParam: () => undefined, - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toEqualTypeOf>() return 'selected' as const }, diff --git a/packages/react-query/src/__tests__/useInfiniteQuery.test.tsx b/packages/react-query/src/__tests__/useInfiniteQuery.test.tsx index 95b596bc1b2..266c51e8564 100644 --- a/packages/react-query/src/__tests__/useInfiniteQuery.test.tsx +++ b/packages/react-query/src/__tests__/useInfiniteQuery.test.tsx @@ -1,4 +1,8 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { + placeholderOption, + selectOption, +} from '@tanstack/query-test-utils/projection' import { fireEvent, render } from '@testing-library/react' import { createRenderStream } from '@testing-library/react-render-stream' import * as React from 'react' @@ -187,7 +191,7 @@ describe('useInfiniteQuery', () => { sleep(10).then(() => `${pageParam}-${order}`), getNextPageParam: () => 1, initialPageParam: 0, - placeholderData: keepPreviousData, + [placeholderOption]: keepPreviousData, notifyOnChangeProps: 'all', }) @@ -271,7 +275,7 @@ describe('useInfiniteQuery', () => { const state = useInfiniteQuery({ queryKey: key, queryFn: () => sleep(10).then(() => ({ count: 1 })), - select: (data) => ({ + [selectOption]: (data) => ({ pages: data.pages.map((x) => `count: ${x.count}`), pageParams: data.pageParams, }), @@ -310,13 +314,16 @@ describe('useInfiniteQuery', () => { const state = useInfiniteQuery({ queryKey: key, queryFn: () => sleep(10).then(() => ({ count: 1 })), - select: React.useCallback((data: InfiniteData<{ count: number }>) => { - selectCalled++ - return { - pages: data.pages.map((x) => ({ ...x, id: Math.random() })), - pageParams: data.pageParams, - } - }, []), + [selectOption]: React.useCallback( + (data: InfiniteData<{ count: number }>) => { + selectCalled++ + return { + pages: data.pages.map((x) => ({ ...x, id: Math.random() })), + pageParams: data.pageParams, + } + }, + [], + ), getNextPageParam: () => undefined, initialPageParam: 0, }) @@ -356,7 +363,7 @@ describe('useInfiniteQuery', () => { const state = useInfiniteQuery({ queryKey: key, queryFn: ({ pageParam }) => sleep(10).then(() => pageParam), - select: (data) => ({ + [selectOption]: (data) => ({ pages: [...data.pages].reverse(), pageParams: [...data.pageParams].reverse(), }), @@ -1429,7 +1436,7 @@ describe('useInfiniteQuery', () => { queryKey: key, queryFn: ({ pageParam }) => sleep(10).then(() => pageParam), getNextPageParam: (lastPage) => (lastPage === 1 ? 2 : undefined), - select: (data) => ({ + [selectOption]: (data) => ({ pages: data.pages.map((x) => x.toString()), pageParams: data.pageParams, }), @@ -1534,7 +1541,9 @@ describe('useInfiniteQuery', () => { // makes an actual network request // and calls invalidateQueries in an onSuccess items.splice(4, 1) - queryClient.invalidateQueries({ queryKey: key }) + queryClient.invalidateQueries({ + queryKey: key, + }) }} > Remove item diff --git a/packages/react-query/src/__tests__/usePrefetchInfiniteQuery.test-d.tsx b/packages/react-query/src/__tests__/usePrefetchInfiniteQuery.test-d.tsx index 6f16f5d178c..c117dc98cc5 100644 --- a/packages/react-query/src/__tests__/usePrefetchInfiniteQuery.test-d.tsx +++ b/packages/react-query/src/__tests__/usePrefetchInfiniteQuery.test-d.tsx @@ -1,4 +1,5 @@ import { createKey } from '@tanstack/query-test-utils' +import { refetchInterval } from '@tanstack/query-test-utils/polling' import { assertType, describe, expectTypeOf, it } from 'vitest' import { skipToken, usePrefetchInfiniteQuery } from '..' @@ -32,7 +33,7 @@ describe('usePrefetchInfiniteQuery', () => { initialPageParam: 1, getNextPageParam: () => 1, // @ts-expect-error TS2353 - refetchInterval: 1000, + refetchInterval: refetchInterval(1000), }), ) diff --git a/packages/react-query/src/__tests__/usePrefetchQuery.test-d.tsx b/packages/react-query/src/__tests__/usePrefetchQuery.test-d.tsx index 700f4e19e46..e156bc4cf03 100644 --- a/packages/react-query/src/__tests__/usePrefetchQuery.test-d.tsx +++ b/packages/react-query/src/__tests__/usePrefetchQuery.test-d.tsx @@ -1,4 +1,6 @@ import { createKey } from '@tanstack/query-test-utils' +import { refetchInterval } from '@tanstack/query-test-utils/polling' +import { selectOption } from '@tanstack/query-test-utils/projection' import { assertType, describe, expectTypeOf, it } from 'vitest' import { skipToken, usePrefetchQuery } from '..' @@ -18,7 +20,7 @@ describe('usePrefetchQuery', () => { queryKey: createKey(), queryFn: () => Promise.resolve(5), // @ts-expect-error TS2345 - refetchInterval: 1000, + refetchInterval: refetchInterval(1000), }), ) @@ -62,7 +64,7 @@ describe('usePrefetchQuery', () => { usePrefetchQuery({ queryKey: createKey(), queryFn: () => Promise.resolve('data'), - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toEqualTypeOf<{ value: string }>() return data.value.length diff --git a/packages/react-query/src/__tests__/useQueries.test-d.tsx b/packages/react-query/src/__tests__/useQueries.test-d.tsx index 5c153b0c504..05c1ce0125a 100644 --- a/packages/react-query/src/__tests__/useQueries.test-d.tsx +++ b/packages/react-query/src/__tests__/useQueries.test-d.tsx @@ -1,4 +1,8 @@ import { createKey } from '@tanstack/query-test-utils' +import { + placeholderOption, + selectOption, +} from '@tanstack/query-test-utils/projection' import { describe, expectTypeOf, it } from 'vitest' import { skipToken } from '..' import { queryOptions } from '../queryOptions' @@ -67,13 +71,13 @@ describe('useQueries', () => { const query1 = queryOptions({ queryKey: createKey(), queryFn: () => Promise.resolve(1), - select: (data) => data > 1, + [selectOption]: (data) => data > 1, }) const query2 = { queryKey: createKey(), queryFn: () => Promise.resolve(1), - select: (data: number) => data > 1, + [selectOption]: (data: number) => data > 1, } const queryResults = useQueries({ queries: [query1, query2] }) @@ -223,7 +227,7 @@ describe('useQueries', () => { { queryKey: key1, queryFn: () => 'string', - select: (a) => { + [selectOption]: (a) => { expectTypeOf(a).toEqualTypeOf() return a.toLowerCase() }, @@ -231,7 +235,7 @@ describe('useQueries', () => { { queryKey: key2, queryFn: () => 'string', - select: (a) => { + [selectOption]: (a) => { expectTypeOf(a).toEqualTypeOf() return parseInt(a) }, @@ -253,22 +257,22 @@ describe('useQueries', () => { { queryKey: key1, queryFn: () => 'string', - select: (a) => { + [selectOption]: (a) => { expectTypeOf(a).toEqualTypeOf() return a.toLowerCase() }, - placeholderData: 'string', + [placeholderOption]: 'string', // @ts-expect-error (initialData: string) initialData: 123, }, { queryKey: key2, queryFn: () => 'string', - select: (a) => { + [selectOption]: (a) => { expectTypeOf(a).toEqualTypeOf() return parseInt(a) }, - placeholderData: 'string', + [placeholderOption]: 'string', // @ts-expect-error (initialData: string) initialData: 123, }, @@ -343,7 +347,7 @@ describe('useQueries', () => { { queryKey: key1, queryFn: () => 'string', - select: (a) => { + [selectOption]: (a) => { expectTypeOf(a).toEqualTypeOf() return a.toLowerCase() }, @@ -351,7 +355,7 @@ describe('useQueries', () => { { queryKey: key2, queryFn: () => 'string', - select: (a) => { + [selectOption]: (a) => { expectTypeOf(a).toEqualTypeOf() return parseInt(a) }, @@ -373,7 +377,7 @@ describe('useQueries', () => { { queryKey: key1, queryFn: () => 'string', - select: (a) => { + [selectOption]: (a) => { expectTypeOf(a).toEqualTypeOf() return a as string }, @@ -381,7 +385,7 @@ describe('useQueries', () => { { queryKey: key2, queryFn: () => 'string', - select: (a) => { + [selectOption]: (a) => { expectTypeOf(a).toEqualTypeOf() return a as number }, @@ -408,22 +412,22 @@ describe('useQueries', () => { { queryKey: key1, queryFn: () => 'string', - select: (a) => { + [selectOption]: (a) => { expectTypeOf(a).toEqualTypeOf() return a.toLowerCase() }, - placeholderData: 'string', + [placeholderOption]: 'string', // @ts-expect-error (initialData: string) initialData: 123, }, { queryKey: key2, queryFn: () => 'string', - select: (a) => { + [selectOption]: (a) => { expectTypeOf(a).toEqualTypeOf() return parseInt(a) }, - placeholderData: 'string', + [placeholderOption]: 'string', // @ts-expect-error (initialData: string) initialData: 123, }, @@ -453,7 +457,7 @@ describe('useQueries', () => { queryOptions({ queryKey: createKey(), queryFn: () => 'string', - select: (a) => { + [selectOption]: (a) => { expectTypeOf(a).toEqualTypeOf() return a.toLowerCase() }, @@ -461,7 +465,7 @@ describe('useQueries', () => { queryOptions({ queryKey: createKey(), queryFn: () => 'string', - select: (a) => { + [selectOption]: (a) => { expectTypeOf(a).toEqualTypeOf() return parseInt(a) }, @@ -522,7 +526,7 @@ describe('useQueries', () => { queries: Array(50).map((_, i) => ({ queryKey: ['key', i] as const, queryFn: () => i + 10, - select: (data: number) => data.toString(), + [selectOption]: (data: number) => data.toString(), })), }) expectTypeOf(result2).toEqualTypeOf< @@ -533,7 +537,7 @@ describe('useQueries', () => { queries: Array(50).map((_, i) => ({ queryKey: ['key', i] as const, queryFn: () => i + 10, - select: (data: number) => data.toString(), + [selectOption]: (data: number) => data.toString(), throwOnError, })), }) @@ -554,7 +558,7 @@ describe('useQueries', () => { { queryKey: key3, queryFn: () => ['string[]'], - select: () => 123, + [selectOption]: () => 123, }, { queryKey: key5, @@ -580,7 +584,7 @@ describe('useQueries', () => { { queryKey: key1, queryFn: () => 'string', - placeholderData: 'string', + [placeholderOption]: 'string', // @ts-expect-error (initialData: string) initialData: 123, }, @@ -588,7 +592,7 @@ describe('useQueries', () => { queryKey: key2, queryFn: () => 123, // @ts-expect-error (placeholderData: number) - placeholderData: 'string', + [placeholderOption]: 'string', initialData: 123, }, ], @@ -615,7 +619,7 @@ describe('useQueries', () => { { queryKey: key4, queryFn: () => 'string', - select: (a: string) => parseInt(a), + [selectOption]: (a: string) => parseInt(a), }, { queryKey: key5, @@ -630,14 +634,14 @@ describe('useQueries', () => { queries: Array(50).map((_, i) => ({ queryKey: ['key', i] as const, queryFn: () => i + 10, - select: (data: number) => data.toString(), + [selectOption]: (data: number) => data.toString(), })), }) useQueries({ queries: Array(50).map((_, i) => ({ queryKey: ['key', i] as const, queryFn: () => i + 10, - select: (data: number) => data.toString(), + [selectOption]: (data: number) => data.toString(), })), }) @@ -655,12 +659,12 @@ describe('useQueries', () => { { queryKey: key4, queryFn: () => 'string', - select: (a: string) => parseInt(a), + [selectOption]: (a: string) => parseInt(a), }, { queryKey: key5, queryFn: () => 'string', - select: (a: string) => parseInt(a), + [selectOption]: (a: string) => parseInt(a), throwOnError, }, ], @@ -838,12 +842,12 @@ describe('useQueries', () => { { queryKey: getQueryKeyA(), queryFn: getQueryFunctionA(), - select: getSelectorA(), + [selectOption]: getSelectorA(), }, { queryKey: getQueryKeyB('id'), queryFn: getQueryFunctionB(), - select: getSelectorB(), + [selectOption]: getSelectorB(), }, ], }) @@ -858,7 +862,7 @@ describe('useQueries', () => { Array(10).map(() => ({ queryKey: getQueryKeyA(), queryFn: getQueryFunctionA(), - select: getSelectorA(), + [selectOption]: getSelectorA(), })), ) @@ -884,7 +888,7 @@ describe('useQueries', () => { { queryKey: createKey(), queryFn: () => Promise.resolve(1), - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toBeUnknown() // @ts-expect-error `data` is `unknown`, not the expected `number` return data.toFixed() @@ -900,7 +904,7 @@ describe('useQueries', () => { { queryKey: createKey(), queryFn: () => Promise.resolve(1), - select: (data: number) => data.toFixed(), + [selectOption]: (data: number) => data.toFixed(), }, ], }) @@ -922,7 +926,7 @@ describe('useQueries', () => { const options = queryOptions({ queryKey: createKey(), queryFn: () => Promise.resolve(1), - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toEqualTypeOf() return data.toFixed() }, @@ -940,7 +944,7 @@ describe('useQueries', () => { queries: [ queryOptions({ ...baseOptions, - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toEqualTypeOf() return data.toFixed() }, @@ -956,13 +960,13 @@ describe('useQueries', () => { const baseOptions = queryOptions({ queryKey: createKey(), queryFn: () => Promise.resolve(1), - select: (data) => data + 1, + [selectOption]: (data) => data + 1, }) const queryResults = useQueries({ queries: [ queryOptions({ ...baseOptions, - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toEqualTypeOf() return data.toFixed() }, @@ -984,7 +988,7 @@ describe('useQueries', () => { // @ts-expect-error Without an annotation the inline `select` receives `data: unknown`, which makes the whole spread query object unassignable to the expected options type { ...options, - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toBeUnknown() return data }, @@ -999,7 +1003,9 @@ describe('useQueries', () => { queryFn: () => Promise.resolve(1), }) const queryResults = useQueries({ - queries: [{ ...options, select: (data: number) => data.toFixed() }], + queries: [ + { ...options, [selectOption]: (data: number) => data.toFixed() }, + ], }) expectTypeOf(queryResults[0].data).toEqualTypeOf() }) @@ -1008,14 +1014,14 @@ describe('useQueries', () => { const options = queryOptions({ queryKey: createKey(), queryFn: () => Promise.resolve(1), - select: (data) => data + 1, + [selectOption]: (data) => data + 1, }) useQueries({ queries: [ // @ts-expect-error Without an annotation the inline `select` receives `data: unknown`, which makes the whole spread query object unassignable to the expected options type { ...options, - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toBeUnknown() return data }, @@ -1028,10 +1034,12 @@ describe('useQueries', () => { const options = queryOptions({ queryKey: createKey(), queryFn: () => Promise.resolve(1), - select: (data) => data + 1, + [selectOption]: (data) => data + 1, }) const queryResults = useQueries({ - queries: [{ ...options, select: (data: number) => data.toFixed() }], + queries: [ + { ...options, [selectOption]: (data: number) => data.toFixed() }, + ], }) expectTypeOf(queryResults[0].data).toEqualTypeOf() }) diff --git a/packages/react-query/src/__tests__/useQueries.test.tsx b/packages/react-query/src/__tests__/useQueries.test.tsx index 2987133043c..dae2db61e75 100644 --- a/packages/react-query/src/__tests__/useQueries.test.tsx +++ b/packages/react-query/src/__tests__/useQueries.test.tsx @@ -1,4 +1,5 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { selectOption } from '@tanstack/query-test-utils/projection' import { fireEvent, render } from '@testing-library/react' import * as React from 'react' import { ErrorBoundary } from 'react-error-boundary' @@ -70,7 +71,7 @@ describe('useQueries', () => { { queryKey: key, queryFn: () => Promise.resolve([1, 2, 3]), - select, + [selectOption]: select, staleTime: Infinity, structuralSharing: false, }, @@ -141,7 +142,7 @@ describe('useQueries', () => { { queryKey, queryFn, - select: (value: string) => { + [selectOption]: (value: string) => { if (throws) throw new Error(value + ' with a select error') return new Set([value]) }, diff --git a/packages/react-query/src/__tests__/useQuery.test-d.tsx b/packages/react-query/src/__tests__/useQuery.test-d.tsx index 3299b16fd4d..2c53fea4242 100644 --- a/packages/react-query/src/__tests__/useQuery.test-d.tsx +++ b/packages/react-query/src/__tests__/useQuery.test-d.tsx @@ -1,4 +1,5 @@ import { createKey } from '@tanstack/query-test-utils' +import { selectOption } from '@tanstack/query-test-utils/projection' import { assertType, describe, expectTypeOf, it } from 'vitest' import { defaultQueryFn } from '..' import { queryOptions } from '../queryOptions' @@ -229,7 +230,7 @@ describe('useQuery', () => { const query = useQuery({ ...options, - select: (data) => data > 1, + [selectOption]: (data) => data > 1, }) expectTypeOf(query.data).toEqualTypeOf() diff --git a/packages/react-query/src/__tests__/useQuery.test.tsx b/packages/react-query/src/__tests__/useQuery.test.tsx index edd9fb80c4b..f1f7fd3d319 100644 --- a/packages/react-query/src/__tests__/useQuery.test.tsx +++ b/packages/react-query/src/__tests__/useQuery.test.tsx @@ -3,6 +3,11 @@ import { mockVisibilityState, sleep, } from '@tanstack/query-test-utils' +import { refetchInterval } from '@tanstack/query-test-utils/polling' +import { + placeholderOption, + selectOption, +} from '@tanstack/query-test-utils/projection' import { act, fireEvent, render, renderHook } from '@testing-library/react' import * as React from 'react' import { ErrorBoundary } from 'react-error-boundary' @@ -89,7 +94,7 @@ describe('useQuery', () => { queryKey: [key, id], queryFn: () => Promise.resolve({ value: id }), staleTime: Infinity, - select, + [selectOption]: select, }) results.push(data) return
    {data?.selected}
    @@ -126,7 +131,7 @@ describe('useQuery', () => { queryKey: key, queryFn: () => Promise.resolve(todos), staleTime: Infinity, - select: React.useCallback( + [selectOption]: React.useCallback( (items: typeof todos) => items.filter((todo) => todo.completed === completed), [completed], @@ -762,7 +767,7 @@ describe('useQuery', () => { const state = useQuery({ queryKey: key, queryFn: () => ({ name: 'test' }), - select: (data) => data.name, + [selectOption]: (data) => data.name, }) states.push(state) @@ -787,7 +792,7 @@ describe('useQuery', () => { const state = useQuery({ queryKey: key, queryFn: () => ({ name: 'test' }), - select: (data) => data.name, + [selectOption]: (data) => data.name, }) states.push(state) @@ -813,7 +818,7 @@ describe('useQuery', () => { const state = useQuery({ queryKey: key, queryFn: () => ({ name: 'test' }), - select: () => { + [selectOption]: () => { throw error }, }) @@ -844,7 +849,7 @@ describe('useQuery', () => { queryKey: key, queryFn: () => (runs === 0 ? 'test' : 'test2'), - select: React.useCallback(() => { + [selectOption]: React.useCallback(() => { runs++ throw error }, []), @@ -1331,7 +1336,7 @@ describe('useQuery', () => { const state = useQuery({ queryKey: [key, count], queryFn: () => sleep(10).then(() => count), - placeholderData: keepPreviousData, + [placeholderOption]: keepPreviousData, }) states.push(state) @@ -1393,10 +1398,10 @@ describe('useQuery', () => { const state = useQuery({ queryKey: [key, count], queryFn: () => sleep(10).then(() => ({ count })), - select(data) { + [selectOption](data) { return data.count }, - placeholderData: keepPreviousData, + [placeholderOption]: keepPreviousData, }) states.push(state) @@ -1459,10 +1464,10 @@ describe('useQuery', () => { const state = useQuery({ queryKey: [key, count], queryFn: () => sleep(10).then(() => ({ count })), - select(data) { + [selectOption](data) { return data.count }, - placeholderData: (prevData, prevQuery) => { + [placeholderOption]: (prevData, prevQuery) => { if (prevQuery) { keys.push(prevQuery.queryKey) } @@ -1508,10 +1513,10 @@ describe('useQuery', () => { const state = useQuery({ queryKey: [key, count], queryFn: () => sleep(10).then(() => ({ count })), - select(data) { + [selectOption](data) { return data.count }, - placeholderData: keepPreviousData, + [placeholderOption]: keepPreviousData, }) states.push(state) @@ -1593,7 +1598,7 @@ describe('useQuery', () => { return Promise.resolve(count) }), retry: false, - placeholderData: keepPreviousData, + [placeholderOption]: keepPreviousData, }) states.push(state) @@ -1684,7 +1689,7 @@ describe('useQuery', () => { queryKey: [key, count], queryFn: () => sleep(10).then(() => count), initialData: 99, - placeholderData: keepPreviousData, + [placeholderOption]: keepPreviousData, }) states.push(state) @@ -1752,7 +1757,7 @@ describe('useQuery', () => { queryKey: [key, count], queryFn: () => sleep(10).then(() => count), enabled: false, - placeholderData: keepPreviousData, + [placeholderOption]: keepPreviousData, notifyOnChangeProps: 'all', }) @@ -1844,7 +1849,7 @@ describe('useQuery', () => { queryKey: [key, count], queryFn: () => sleep(10).then(() => count), enabled: false, - placeholderData: keepPreviousData, + [placeholderOption]: keepPreviousData, notifyOnChangeProps: 'all', }) @@ -2152,7 +2157,7 @@ describe('useQuery', () => { const state = useQuery({ queryKey: key, queryFn: () => ({ name: 'test' }), - select: (data) => data.name, + [selectOption]: (data) => data.name, }) states.push(state) @@ -3796,7 +3801,7 @@ describe('useQuery', () => { initialData() { return filter === '' ? initialTodos : undefined }, - placeholderData: keepPreviousData, + [placeholderOption]: keepPreviousData, staleTime: 5000, }) @@ -4039,7 +4044,7 @@ describe('useQuery', () => { const { data } = useQuery({ queryKey: key, queryFn: () => count++, - refetchInterval: int, + refetchInterval: refetchInterval(int), }) React.useEffect(() => { @@ -4071,7 +4076,8 @@ describe('useQuery', () => { const queryInfo = useQuery({ queryKey: key, queryFn: () => sleep(10).then(() => count++), - refetchInterval: ({ state: { data = 0 } }) => (data < 2 ? 10 : false), + refetchInterval: ({ state: { data = 0 } }) => + refetchInterval(data < 2 ? 10 : false), }) states.push(queryInfo) @@ -4135,7 +4141,7 @@ describe('useQuery', () => { const queryInfo = useQuery({ queryKey: key, queryFn, - refetchInterval: 0, + refetchInterval: refetchInterval(0), }) return
    count: {queryInfo.data}
    @@ -4222,7 +4228,7 @@ describe('useQuery', () => { const state = useQuery({ queryKey: key1, queryFn: () => 'data', - placeholderData: 'placeholder', + [placeholderOption]: 'placeholder', }) states.push(state) @@ -4265,7 +4271,7 @@ describe('useQuery', () => { const state = useQuery({ queryKey: key1, queryFn: () => 'data', - placeholderData: 'placeholder', + [placeholderOption]: 'placeholder', enabled: count === 0, }) @@ -4325,8 +4331,8 @@ describe('useQuery', () => { const state = useQuery({ queryKey: key1, queryFn: () => 1, - placeholderData: 23, - select: (data) => String(data * 2), + [placeholderOption]: 23, + [selectOption]: (data) => String(data * 2), }) states.push(state) @@ -4368,11 +4374,11 @@ describe('useQuery', () => { const state = useQuery({ queryKey: key1, queryFn: () => 1, - placeholderData: () => { + [placeholderOption]: () => { placeholderFunctionRunCount++ return 23 }, - select: (data) => String(data * 2), + [selectOption]: (data) => String(data * 2), }) states.push(state) @@ -4424,14 +4430,14 @@ describe('useQuery', () => { const state = useQuery({ queryKey: key1, queryFn: () => sleep(10).then(() => 0), - select: React.useCallback( + [selectOption]: React.useCallback( (data: number) => { selectRun++ return `selected ${data + count}` }, [count], ), - placeholderData: 99, + [placeholderOption]: 99, }) return ( @@ -4467,13 +4473,13 @@ describe('useQuery', () => { queryKey: key1, queryFn: () => sleep(10).then(() => 0), - select: React.useCallback( + [selectOption]: React.useCallback( (data: number) => { return `selected ${data + count}` }, [count], ), - placeholderData: 99, + [placeholderOption]: 99, }) return ( @@ -4514,7 +4520,7 @@ describe('useQuery', () => { queryKey: key1, queryFn: () => sleep(10).then(() => [1, 2]), - select: (res) => res.map((x) => x + 1), + [selectOption]: (res) => res.map((x) => x + 1), }) React.useEffect(() => { @@ -5216,7 +5222,11 @@ describe('useQuery', () => {
    failureReason: {state.failureReason ?? 'null'}
    data: {state.data}
    @@ -5274,7 +5284,11 @@ describe('useQuery', () => {
    data: {state.data}
    @@ -5320,7 +5334,11 @@ describe('useQuery', () => {
    data: {state.data}
    @@ -5365,7 +5383,11 @@ describe('useQuery', () => {
    data: {state.data}
    @@ -5411,7 +5433,11 @@ describe('useQuery', () => {
    data: {state.data}
    @@ -5692,7 +5718,11 @@ describe('useQuery', () => { {show && } @@ -6179,7 +6209,7 @@ describe('useQuery', () => { const [id, setId] = React.useState(1) const { data } = useQuery({ - select: selector, + [selectOption]: selector, queryKey: [key, 'user', id], queryFn: () => fetchNumber(id), }) @@ -6246,10 +6276,10 @@ describe('useQuery', () => { const [id, setId] = React.useState(1) const { data } = useQuery({ - select: selector, + [selectOption]: selector, queryKey: [key, 'user', id], queryFn: () => fetchNumber(id), - placeholderData: { numbers: { current: { id: 99 } } }, + [placeholderOption]: { numbers: { current: { id: 99 } } }, }) React.useEffect(() => { @@ -6335,7 +6365,7 @@ describe('useQuery', () => { staleTime: Infinity, queryKey: [key, steps[count]], queryFn: () => sleep(10).then(() => steps[count]), - placeholderData: keepPreviousData, + [placeholderOption]: keepPreviousData, }) states.push(state) @@ -7121,8 +7151,8 @@ describe('useQuery', () => { queryKey: [...key, id], queryFn: () => [id], enabled: id !== '', - placeholderData: keepPreviousData, - select: (items) => items.find((item) => item === id), + [placeholderOption]: keepPreviousData, + [selectOption]: (items) => items.find((item) => item === id), }) return ( @@ -7149,8 +7179,8 @@ describe('useQuery', () => { queryKey: [...key, id], queryFn: () => [id], enabled: id !== '', - placeholderData: keepPreviousData, - select: (items) => items.find((item) => item === id), + [placeholderOption]: keepPreviousData, + [selectOption]: (items) => items.find((item) => item === id), }) states.push(state) diff --git a/packages/react-query/src/__tests__/useSuspenseInfiniteQuery.test-d.tsx b/packages/react-query/src/__tests__/useSuspenseInfiniteQuery.test-d.tsx index 514151b4c40..91a4235f639 100644 --- a/packages/react-query/src/__tests__/useSuspenseInfiniteQuery.test-d.tsx +++ b/packages/react-query/src/__tests__/useSuspenseInfiniteQuery.test-d.tsx @@ -1,5 +1,9 @@ import { keepPreviousData, skipToken } from '@tanstack/query-core' import { createKey } from '@tanstack/query-test-utils' +import { + placeholderOption, + selectOption, +} from '@tanstack/query-test-utils/projection' import { assertType, describe, expectTypeOf, it } from 'vitest' import { useSuspenseInfiniteQuery } from '../useSuspenseInfiniteQuery' import type { InfiniteData } from '@tanstack/query-core' @@ -26,7 +30,7 @@ describe('useSuspenseInfiniteQuery', () => { : ({ pageParam }) => pageParam.toFixed(), initialPageParam: 1, getNextPageParam: () => undefined, - select: (data) => data.pages, + [selectOption]: (data) => data.pages, }) expectTypeOf(result.data).toEqualTypeOf | undefined>() @@ -54,7 +58,7 @@ describe('useSuspenseInfiniteQuery', () => { queryFn: () => Promise.resolve(5), initialPageParam: 1, getNextPageParam: () => 1, - placeholderData: keepPreviousData, + [placeholderOption]: keepPreviousData, }) expectTypeOf(query.data).toEqualTypeOf>() @@ -65,13 +69,13 @@ describe('useSuspenseInfiniteQuery', () => { queryFn: () => Promise.resolve(5), initialPageParam: 1, getNextPageParam: () => 1, - placeholderData: (previousData) => { + [placeholderOption]: (previousData) => { expectTypeOf(previousData).toEqualTypeOf< InfiniteData | undefined >() return previousData ?? { pages: [0], pageParams: [1] } }, - select: (data) => data.pages.length, + [selectOption]: (data) => data.pages.length, }) expectTypeOf(selected.data).toEqualTypeOf() @@ -84,7 +88,7 @@ describe('useSuspenseInfiniteQuery', () => { queryFn: () => Promise.resolve(5), initialPageParam: 1, getNextPageParam: () => 1, - placeholderData: { pages: [5], pageParams: [1] }, + [placeholderOption]: { pages: [5], pageParams: [1] }, // @ts-expect-error TS2345 enabled: true, }), diff --git a/packages/react-query/src/__tests__/useSuspenseInfiniteQuery.test.tsx b/packages/react-query/src/__tests__/useSuspenseInfiniteQuery.test.tsx index 09f5d8aeaeb..3f417bc491f 100644 --- a/packages/react-query/src/__tests__/useSuspenseInfiniteQuery.test.tsx +++ b/packages/react-query/src/__tests__/useSuspenseInfiniteQuery.test.tsx @@ -1,4 +1,5 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { placeholderOption } from '@tanstack/query-test-utils/projection' import { act, fireEvent } from '@testing-library/react' import * as React from 'react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -131,7 +132,7 @@ describe('useSuspenseInfiniteQuery', () => { queryFn, initialPageParam: 1, getNextPageParam: () => undefined, - placeholderData: { pages: [0], pageParams: [1] }, + [placeholderOption]: { pages: [0], pageParams: [1] }, }) states.push(state) @@ -157,7 +158,7 @@ describe('useSuspenseInfiniteQuery', () => { const queryClientWithPlaceholder = new QueryClient({ defaultOptions: { queries: { - placeholderData: keepPreviousData, + [placeholderOption]: keepPreviousData, }, }, }) @@ -230,7 +231,7 @@ describe('useSuspenseInfiniteQuery', () => { queryFn: () => queryFn(count), initialPageParam: 1, getNextPageParam: () => undefined, - placeholderData: keepPreviousData, + [placeholderOption]: keepPreviousData, }) return ( diff --git a/packages/react-query/src/__tests__/useSuspenseQueries.test-d.tsx b/packages/react-query/src/__tests__/useSuspenseQueries.test-d.tsx index a18946b0fc0..05fba69fa2b 100644 --- a/packages/react-query/src/__tests__/useSuspenseQueries.test-d.tsx +++ b/packages/react-query/src/__tests__/useSuspenseQueries.test-d.tsx @@ -1,4 +1,8 @@ import { createKey } from '@tanstack/query-test-utils' +import { + placeholderOption, + selectOption, +} from '@tanstack/query-test-utils/projection' import { assertType, describe, expectTypeOf, it } from 'vitest' import { skipToken, useSuspenseQueries } from '..' import { queryOptions } from '../queryOptions' @@ -39,7 +43,7 @@ describe('UseSuspenseQueries config object overload', () => { { queryKey: createKey(), queryFn: () => Promise.resolve(5), - placeholderData: (previousData, previousQuery) => { + [placeholderOption]: (previousData, previousQuery) => { expectTypeOf(previousData).toEqualTypeOf() expectTypeOf(previousQuery).toEqualTypeOf() return 0 @@ -54,8 +58,8 @@ describe('UseSuspenseQueries config object overload', () => { const selectedOptions = queryOptions({ queryKey: createKey(), queryFn: () => Promise.resolve(5), - placeholderData: 0, - select: (data) => data.toString(), + [placeholderOption]: 0, + [selectOption]: (data) => data.toString(), }) const [selectedQuery] = useSuspenseQueries({ queries: [selectedOptions], @@ -84,13 +88,13 @@ describe('UseSuspenseQueries config object overload', () => { const query1 = queryOptions({ queryKey: createKey(), queryFn: () => Promise.resolve(1), - select: (data) => data > 1, + [selectOption]: (data) => data > 1, }) const query2 = { queryKey: createKey(), queryFn: () => Promise.resolve(1), - select: (data: number) => data > 1, + [selectOption]: (data: number) => data > 1, } const queryResults = useSuspenseQueries({ queries: [query1, query2] }) @@ -213,7 +217,7 @@ describe('UseSuspenseQueries config object overload', () => { ...queries1List, { ...Queries2.get(), - select(data: boolean) { + [selectOption](data: boolean) { return data }, }, @@ -277,7 +281,7 @@ describe('UseSuspenseQueries config object overload', () => { queryKey: createKey(), queryFn: () => 'Query Data', }), - select(data: string) { + [selectOption](data: string) { return data }, }, @@ -301,7 +305,7 @@ describe('UseSuspenseQueries config object overload', () => { { queryKey: createKey(), queryFn: () => Promise.resolve(1), - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toBeUnknown() // @ts-expect-error `data` is `unknown`, not the expected `number` return data.toFixed() @@ -317,7 +321,7 @@ describe('UseSuspenseQueries config object overload', () => { { queryKey: createKey(), queryFn: () => Promise.resolve(1), - select: (data: number) => data.toFixed(), + [selectOption]: (data: number) => data.toFixed(), }, ], }) @@ -339,7 +343,7 @@ describe('UseSuspenseQueries config object overload', () => { const options = queryOptions({ queryKey: createKey(), queryFn: () => Promise.resolve(1), - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toEqualTypeOf() return data.toFixed() }, @@ -357,7 +361,7 @@ describe('UseSuspenseQueries config object overload', () => { queries: [ queryOptions({ ...baseOptions, - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toEqualTypeOf() return data.toFixed() }, @@ -373,13 +377,13 @@ describe('UseSuspenseQueries config object overload', () => { const baseOptions = queryOptions({ queryKey: createKey(), queryFn: () => Promise.resolve(1), - select: (data) => data + 1, + [selectOption]: (data) => data + 1, }) const queryResults = useSuspenseQueries({ queries: [ queryOptions({ ...baseOptions, - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toEqualTypeOf() return data.toFixed() }, @@ -401,7 +405,7 @@ describe('UseSuspenseQueries config object overload', () => { { ...options, // @ts-expect-error Without an annotation the inline `select` parameter `data` implicitly has type `any` - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toBeAny() return data }, @@ -416,7 +420,9 @@ describe('UseSuspenseQueries config object overload', () => { queryFn: () => Promise.resolve(1), }) const queryResults = useSuspenseQueries({ - queries: [{ ...options, select: (data: number) => data.toFixed() }], + queries: [ + { ...options, [selectOption]: (data: number) => data.toFixed() }, + ], }) expectTypeOf(queryResults[0].data).toEqualTypeOf() }) @@ -425,14 +431,14 @@ describe('UseSuspenseQueries config object overload', () => { const options = queryOptions({ queryKey: createKey(), queryFn: () => Promise.resolve(1), - select: (data) => data + 1, + [selectOption]: (data) => data + 1, }) useSuspenseQueries({ queries: [ { ...options, // @ts-expect-error Without an annotation the inline `select` parameter `data` implicitly has type `any` - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toBeAny() return data }, @@ -445,10 +451,12 @@ describe('UseSuspenseQueries config object overload', () => { const options = queryOptions({ queryKey: createKey(), queryFn: () => Promise.resolve(1), - select: (data) => data + 1, + [selectOption]: (data) => data + 1, }) const queryResults = useSuspenseQueries({ - queries: [{ ...options, select: (data: number) => data.toFixed() }], + queries: [ + { ...options, [selectOption]: (data: number) => data.toFixed() }, + ], }) expectTypeOf(queryResults[0].data).toEqualTypeOf() }) diff --git a/packages/react-query/src/__tests__/useSuspenseQueries.test.tsx b/packages/react-query/src/__tests__/useSuspenseQueries.test.tsx index f2841390c03..036b867873e 100644 --- a/packages/react-query/src/__tests__/useSuspenseQueries.test.tsx +++ b/packages/react-query/src/__tests__/useSuspenseQueries.test.tsx @@ -1,4 +1,8 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { + placeholderOption, + selectOption, +} from '@tanstack/query-test-utils/projection' import { act, fireEvent, render } from '@testing-library/react' import * as React from 'react' import { ErrorBoundary } from 'react-error-boundary' @@ -384,14 +388,14 @@ describe('useSuspenseQueries', () => { function getName() { return { ...getUserData(), - select: (data: any) => data.name, + [selectOption]: (data: any) => data.name, } } function getAge() { return { ...getUserData(), - select: (data: any) => data.age, + [selectOption]: (data: any) => data.age, } } @@ -686,7 +690,7 @@ describe('useSuspenseQueries', () => { queryKey: key, queryFn: () => Promise.resolve('First'), staleTime: Infinity, - select: (data: string) => + [selectOption]: (data: string) => expanded ? data.toUpperCase() : data.toLowerCase(), }, ...(expanded @@ -838,7 +842,7 @@ describe('useSuspenseQueries', () => { const queryClientWithPlaceholder = new QueryClient({ defaultOptions: { queries: { - placeholderData: 'placeholder', + [placeholderOption]: 'placeholder', }, }, }) @@ -930,7 +934,7 @@ describe('useSuspenseQueries', () => { { queryKey: [...key, 1], queryFn: placeholderQueryFn, - placeholderData: 'placeholder', + [placeholderOption]: 'placeholder', }, { queryKey: [...key, 2], queryFn: pendingQueryFn }, ], @@ -975,7 +979,7 @@ describe('useSuspenseQueries', () => { { queryKey: [...key, deferredCount], queryFn: () => queryFn(deferredCount), - placeholderData: 'placeholder', + [placeholderOption]: 'placeholder', }, ], }) diff --git a/packages/react-query/src/__tests__/useSuspenseQuery.test-d.tsx b/packages/react-query/src/__tests__/useSuspenseQuery.test-d.tsx index d2935226a44..d68b299861e 100644 --- a/packages/react-query/src/__tests__/useSuspenseQuery.test-d.tsx +++ b/packages/react-query/src/__tests__/useSuspenseQuery.test-d.tsx @@ -1,5 +1,9 @@ import { keepPreviousData, skipToken } from '@tanstack/query-core' import { createKey } from '@tanstack/query-test-utils' +import { + placeholderOption, + selectOption, +} from '@tanstack/query-test-utils/projection' import { assertType, describe, expectTypeOf, it } from 'vitest' import { useSuspenseQuery } from '../useSuspenseQuery' @@ -32,7 +36,7 @@ describe('useSuspenseQuery', () => { const result = useSuspenseQuery({ queryKey: createKey(), queryFn: Math.random() > 0.5 ? skipToken : () => Promise.resolve(5), - select: (data) => data.toString(), + [selectOption]: (data) => data.toString(), }) expectTypeOf(result.data).toEqualTypeOf() @@ -48,7 +52,7 @@ describe('useSuspenseQuery', () => { const query = useSuspenseQuery({ queryKey: createKey(), queryFn: () => Promise.resolve(5), - placeholderData: (previousData, previousQuery) => { + [placeholderOption]: (previousData, previousQuery) => { expectTypeOf(previousData).toEqualTypeOf() expectTypeOf(previousQuery).not.toBeAny() return previousData ?? 0 @@ -62,15 +66,15 @@ describe('useSuspenseQuery', () => { useSuspenseQuery({ queryKey: createKey(), queryFn: () => Promise.resolve(5), - placeholderData: keepPreviousData, + [placeholderOption]: keepPreviousData, }), ) const selected = useSuspenseQuery({ queryKey: createKey(), queryFn: () => Promise.resolve(5), - placeholderData: 0, - select: (data) => data.toString(), + [placeholderOption]: 0, + [selectOption]: (data) => data.toString(), }) expectTypeOf(selected.data).toEqualTypeOf() @@ -86,7 +90,7 @@ describe('useSuspenseQuery', () => { useSuspenseQuery({ queryKey: createKey(), queryFn: () => Promise.resolve(5), - placeholderData: 5, + [placeholderOption]: 5, // @ts-expect-error TS2345 enabled: true, }), diff --git a/packages/react-query/src/__tests__/useSuspenseQuery.test.tsx b/packages/react-query/src/__tests__/useSuspenseQuery.test.tsx index 67b5d31e6ca..47f48136f22 100644 --- a/packages/react-query/src/__tests__/useSuspenseQuery.test.tsx +++ b/packages/react-query/src/__tests__/useSuspenseQuery.test.tsx @@ -1,4 +1,9 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { refetchInterval } from '@tanstack/query-test-utils/polling' +import { + placeholderOption, + selectOption, +} from '@tanstack/query-test-utils/projection' import { act, fireEvent } from '@testing-library/react' import * as React from 'react' import { ErrorBoundary } from 'react-error-boundary' @@ -629,7 +634,7 @@ describe('useSuspenseQuery', () => { useSuspenseQuery({ queryKey: key, queryFn: () => sleep(10).then(() => ({ a: { b: 'c' } })), - select: () => { + [selectOption]: () => { throw new Error('foo') }, }) @@ -911,7 +916,7 @@ describe('useSuspenseQuery', () => { const state = useSuspenseQuery({ queryKey: [...key, 'detail', 1], queryFn, - placeholderData: () => + [placeholderOption]: () => queryClient .getQueryData>([...key, 'list']) ?.find((item) => item.id === 1), @@ -948,7 +953,7 @@ describe('useSuspenseQuery', () => { const queryClientWithPlaceholder = new QueryClient({ defaultOptions: { queries: { - placeholderData: keepPreviousData, + [placeholderOption]: keepPreviousData, }, }, }) @@ -1016,7 +1021,7 @@ describe('useSuspenseQuery', () => { const state = useSuspenseQuery({ queryKey: key, queryFn: () => sleep(10).then(() => 'data'), - placeholderData: () => undefined, + [placeholderOption]: () => undefined, }) return
    data: {state.data}
    @@ -1039,7 +1044,7 @@ describe('useSuspenseQuery', () => { const state = useSuspenseQuery({ queryKey: key, queryFn, - placeholderData: showPlaceholder ? 'placeholder' : undefined, + [placeholderOption]: showPlaceholder ? 'placeholder' : undefined, }) return
    data: {state.data}
    @@ -1089,7 +1094,7 @@ describe('useSuspenseQuery', () => { const state = useSuspenseQuery({ queryKey: key, queryFn, - placeholderData: 'placeholder', + [placeholderOption]: 'placeholder', retry: false, }) @@ -1211,7 +1216,7 @@ describe('useSuspenseQuery', () => { const state = useSuspenseQuery({ queryKey: key, queryFn: () => sleep(10).then(() => ++count), - refetchInterval: 10, + refetchInterval: refetchInterval(10), }) return
    count: {state.data}
    diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 65452fc2569..0769614faab 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -406,7 +406,7 @@ importers: version: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0) vitest: specifier: ^5.0.5 - version: 5.0.5(@types/node@24.19.2)(@vitest/coverage-istanbul@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + version: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) examples/angular/auto-refetching: dependencies: @@ -7258,6 +7258,40 @@ importers: specifier: ^6.0.3 version: 6.0.3 + integrations/react/bundle-size: + dependencies: + '@tanstack/react-query': + specifier: workspace:* + version: link:../../../packages/react-query + '@tanstack/react-query-pluggable': + specifier: workspace:* + version: link:../../../packages/react-query-pluggable + react: + specifier: 'catalog:' + version: 19.3.1 + react-dom: + specifier: 'catalog:' + version: 19.3.1(react@19.3.1) + devDependencies: + '@vitest/browser-playwright': + specifier: 5.0.5 + version: 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(playwright@1.65.1)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1))(vitest@5.0.5) + '@vitest/ui': + specifier: 5.0.5 + version: 5.0.5(vitest@5.0.5) + playwright: + specifier: 1.65.1 + version: 1.65.1 + rollup-plugin-visualizer: + specifier: 7.1.1 + version: 7.1.1(rolldown@1.3.1)(rollup@4.65.1) + vite: + specifier: ^8.3.8 + version: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1) + vitest: + specifier: ^5.0.5 + version: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) + integrations/react/next-14: dependencies: '@tanstack/react-query': @@ -7347,9 +7381,15 @@ importers: integrations/react/nodenext: dependencies: + '@tanstack/query-core': + specifier: workspace:* + version: link:../../../packages/query-core '@tanstack/react-query': specifier: workspace:* version: link:../../../packages/react-query + '@tanstack/react-query-pluggable': + specifier: workspace:* + version: link:../../../packages/react-query-pluggable devDependencies: '@types/react': specifier: ^19.3.0 @@ -7774,7 +7814,7 @@ importers: version: 5.1.4(supports-color@10.2.2)(typescript@6.0.3)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) vitest: specifier: ^5.0.5 - version: 5.0.5(@types/node@24.19.2)(@vitest/coverage-istanbul@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) + version: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) zone.js: specifier: ^0.16.0 version: 0.16.1 @@ -8068,7 +8108,7 @@ importers: dependencies: vitest: specifier: ^5.0.5 - version: 5.0.5(@types/node@24.19.2)(@vitest/coverage-istanbul@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + version: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) devDependencies: typescript: specifier: 'catalog:' @@ -8212,6 +8252,37 @@ importers: specifier: 'catalog:' version: 6.0.3 + packages/react-query-pluggable: + dependencies: + '@tanstack/query-core': + specifier: workspace:* + version: link:../query-core + devDependencies: + '@eslint-react/eslint-plugin': + specifier: 'catalog:' + version: 5.28.8(eslint@9.39.5(jiti@2.7.0)(supports-color@10.2.2))(supports-color@10.2.2)(typescript@6.0.3) + '@testing-library/react': + specifier: 'catalog:' + version: 16.3.2(@testing-library/dom@10.4.1)(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + '@types/react': + specifier: ^19.3.0 + version: 19.3.0 + '@types/react-dom': + specifier: ^19.3.0 + version: 19.3.0(@types/react@19.3.0) + eslint-plugin-react-hooks: + specifier: 'catalog:' + version: 7.1.1(eslint@9.39.5(jiti@2.7.0)(supports-color@10.2.2))(supports-color@10.2.2) + react: + specifier: 'catalog:' + version: 19.3.1 + react-dom: + specifier: 'catalog:' + version: 19.3.1(react@19.3.1) + typescript: + specifier: 'catalog:' + version: 6.0.3 + packages/solid-query: dependencies: '@tanstack/query-core': @@ -9672,6 +9743,9 @@ packages: resolution: {integrity: sha512-eBREGwDHRPHtdsg44t071GE2KRDEuJrf0J2uT5/qvJPB2+pfPZOKlx93dMZOFkE7QW5G0JWoczySD7a01Jf0iw==} engines: {node: ^22.18.0 || >=24.11.0} + '@blazediff/core@1.10.0': + resolution: {integrity: sha512-AOQff0zgR7cGsZL+4E7hVkmujoPUpm0J9xzWGWZj5wCjd3gmxESXAPfKyuzs93VdpQNFhHlBhfOjrcZ+XTERtQ==} + '@bomb.sh/tab@0.0.19': resolution: {integrity: sha512-dTRfo9Q9B+lbLG3JCu8a/AGQSfD2XXcFcnakQzVjSOX+VvR/s9zpsH8TlqV3iHqazniRn1Ypwd1hcRlXcu/4BA==} hasBin: true @@ -15239,6 +15313,17 @@ packages: vite: ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0 vue: ^3.2.25 || ^3.6.0-rc.10 + '@vitest/browser-playwright@5.0.5': + resolution: {integrity: sha512-lcdThFUUcMV9mGGV1SUiZXPxfjgW4CssA7o3STxzh8WK0tT2r526kc12tZIBRZfoLMwkhxjLmMXkWXONzdsDQw==} + peerDependencies: + playwright: '*' + vitest: 5.0.5 + + '@vitest/browser@5.0.5': + resolution: {integrity: sha512-IDMoZX/iZ8rkilw7weaSgN8tJ7iZ9hUv0wYoKXyiyjWjWFwLSWAY707DcVTgxTYOudWC1E3HA9LYn7kVa9a7uQ==} + peerDependencies: + vitest: 5.0.5 + '@vitest/coverage-istanbul@5.0.5': resolution: {integrity: sha512-nmbE0+e1JSH9kYEoHGp/iKCQq6+TqwvQ4EcH2zKPULOIrY7rPHxDHsipYGGr+0xMDdzCy46F8zj3edz8dsqvdg==} peerDependencies: @@ -15287,9 +15372,20 @@ packages: vite: optional: true + '@vitest/pretty-format@5.0.5': + resolution: {integrity: sha512-24sSdIlMA9DVPXnYiB9siwU0bTd887Y9jX3+vabztCSsvHwo7ipvJ/a2L3Rljw8+2rK1f5fCj3h5U9I/Jsqgbw==} + '@vitest/spy@5.0.5': resolution: {integrity: sha512-lwJRExuH417257Q5wv9QYugN9IMJkoxcrKrYxGPQkBzl7wlNpTUxD/5yNX4ESKVUIShKPgkGchYPFMWOOk0wzw==} + '@vitest/ui@5.0.5': + resolution: {integrity: sha512-dCoGUOdgmCaSB2g+WQ/spPCBkytAWdNUkFSXY4z+eYp2d8JEOY8v0uDRaJTG9qf/kTlTVZ4CuYMYMz/f1HS/qQ==} + peerDependencies: + vitest: 5.0.5 + + '@vitest/utils@5.0.5': + resolution: {integrity: sha512-/rBu7gzLDQI/SC79Tn98b5DwOgaHU/Gt4I9OVeP3YofzNaYtbImRCOJQmT1S6vOJg9gEIlWC+r3QxKkjuSa1nQ==} + '@volar/kit@2.4.28': resolution: {integrity: sha512-cKX4vK9dtZvDRaAzeoUdaAJEew6IdxHNCRrdp5Kvcl6zZOqb6jTOfk3kXkIkG3T7oTFXguEMt5+9ptyqYR84Pg==} peerDependencies: @@ -17958,8 +18054,8 @@ packages: resolution: {integrity: sha512-b6suED+5/3rTpUBdG1gupIl8MPFCAMA0QXwmljLhvCUKcUvdE4gWky9zpuGCcXHOsz4J9wPGNWq6OKpmIzz3hQ==} hasBin: true - flatted@3.4.2: - resolution: {integrity: sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA==} + flatted@3.4.4: + resolution: {integrity: sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==} flattie@1.1.1: resolution: {integrity: sha512-9UbaD6XdAL97+k/n+N7JwX46K/M6Zc6KcFYskrYL8wbBV/Uyk0CTAMY0VT+qiK5PM7AIc9aTWYtq65U7T+aCNQ==} @@ -20440,6 +20536,16 @@ packages: pkg-types@2.4.0: resolution: {integrity: sha512-07Fys7iVx0X6TcviMOgogM1Lk33ZyqOezMnU79S+kffWqwolG/5W9V8EgQSeYCIfFTYVgssRbnH630Oa2+soBA==} + playwright-core@1.65.1: + resolution: {integrity: sha512-hqPpz7blSMPxWVdoeE1yiBSzXsKiVOd2k+kjCvmUywD2GPO2Dd9HfcWnq9NN0GHbNZDFgZ9JfBFr+X5/BLo0qw==} + engines: {node: '>=20'} + hasBin: true + + playwright@1.65.1: + resolution: {integrity: sha512-vJ1FuoOrNwOKHUIVEvSt3jT1L+wjjDpwhwIstKtfvTh8XIG4FG4bIFuvNdMxi81LGfAhUgUZleVFaOLY4RIUUw==} + engines: {node: '>=20'} + hasBin: true + plist@3.1.0: resolution: {integrity: sha512-uysumyrvkUX0rX/dEVqt8gC3sTBzd4zoWfLeS29nb53imdaXVvLINYXTI2GNqzaMuvacNx4uJQ8+b3zXR0pkgQ==} engines: {node: '>=10.4.0'} @@ -20452,6 +20558,10 @@ packages: resolution: {integrity: sha512-NCrCHhWmnQklfH4MtJMRjZ2a8c80qXeMlQMv2uVp9ISJMTt562SbGd6n2oq0PaPgKm7Z6pL9E2UlLIhC+SHL3w==} engines: {node: '>=4.0.0'} + pngjs@7.0.0: + resolution: {integrity: sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow==} + engines: {node: '>=14.19.0'} + possible-typed-array-names@1.1.0: resolution: {integrity: sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==} engines: {node: '>= 0.4'} @@ -23748,7 +23858,7 @@ snapshots: postcss: 8.5.32 rollup: 4.65.1 tailwindcss: 4.3.3 - vitest: 5.0.5(@types/node@24.19.2)(@vitest/coverage-istanbul@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) + vitest: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) transitivePeerDependencies: - '@types/node' - '@vitejs/devtools' @@ -23812,7 +23922,7 @@ snapshots: postcss: 8.5.32 rollup: 4.65.1 tailwindcss: 4.3.3 - vitest: 5.0.5(@types/node@24.19.2)(@vitest/coverage-istanbul@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + vitest: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) transitivePeerDependencies: - '@types/node' - '@vitejs/devtools' @@ -25302,6 +25412,8 @@ snapshots: '@babel/helper-string-parser': 8.1.3 '@babel/helper-validator-identifier': 8.0.6 + '@blazediff/core@1.10.0': {} + '@bomb.sh/tab@0.0.19(cac@6.7.14)(citty@0.2.2)': optionalDependencies: cac: 6.7.14 @@ -31845,7 +31957,7 @@ snapshots: svelte: 5.57.1(@typescript-eslint/types@8.72.2) optionalDependencies: vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0) - vitest: 5.0.5(@types/node@24.19.2)(@vitest/coverage-istanbul@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + vitest: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) '@tsconfig/svelte@5.0.8': {} @@ -32557,6 +32669,70 @@ snapshots: vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1) vue: 3.5.44(typescript@6.0.3) + '@vitest/browser-playwright@5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(playwright@1.65.1)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(vitest@5.0.5)': + dependencies: + '@vitest/browser': 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(vitest@5.0.5) + '@vitest/mocker': 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + playwright: 1.65.1 + tinyrainbow: 3.2.0 + vitest: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + transitivePeerDependencies: + - bufferutil + - msw + - utf-8-validate + - vite + optional: true + + '@vitest/browser-playwright@5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(playwright@1.65.1)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1))(vitest@5.0.5)': + dependencies: + '@vitest/browser': 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1))(vitest@5.0.5) + '@vitest/mocker': 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) + playwright: 1.65.1 + tinyrainbow: 3.2.0 + vitest: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) + transitivePeerDependencies: + - bufferutil + - msw + - utf-8-validate + - vite + + '@vitest/browser@5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(vitest@5.0.5)': + dependencies: + '@blazediff/core': 1.10.0 + '@vitest/mocker': 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + '@vitest/ui': 5.0.5(vitest@5.0.5) + '@vitest/utils': 5.0.5 + magic-string: 1.4.5 + pngjs: 7.0.0 + sirv: 3.0.2 + tinyrainbow: 3.2.0 + vitest: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + ws: 8.22.1 + transitivePeerDependencies: + - bufferutil + - msw + - utf-8-validate + - vite + optional: true + + '@vitest/browser@5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1))(vitest@5.0.5)': + dependencies: + '@blazediff/core': 1.10.0 + '@vitest/mocker': 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) + '@vitest/ui': 5.0.5(vitest@5.0.5) + '@vitest/utils': 5.0.5 + magic-string: 1.4.5 + pngjs: 7.0.0 + sirv: 3.0.2 + tinyrainbow: 3.2.0 + vitest: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) + ws: 8.22.1 + transitivePeerDependencies: + - bufferutil + - msw + - utf-8-validate + - vite + '@vitest/coverage-istanbul@5.0.5(vitest@5.0.5)': dependencies: '@jridgewell/gen-mapping': 0.3.13 @@ -32568,7 +32744,7 @@ snapshots: magicast: 0.5.5 obug: 3.0.0 tinyrainbow: 3.2.0 - vitest: 5.0.5(@types/node@24.19.2)(@vitest/coverage-istanbul@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + vitest: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) '@vitest/eslint-plugin@1.6.28(@typescript-eslint/eslint-plugin@8.72.2(@typescript-eslint/parser@8.72.2(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@6.0.3))(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@6.0.3))(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@6.0.3)(vitest@5.0.5)': dependencies: @@ -32578,7 +32754,7 @@ snapshots: optionalDependencies: '@typescript-eslint/eslint-plugin': 8.72.2(@typescript-eslint/parser@8.72.2(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@6.0.3))(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@6.0.3) typescript: 6.0.3 - vitest: 5.0.5(@types/node@24.19.2)(@vitest/coverage-istanbul@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + vitest: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) transitivePeerDependencies: - supports-color @@ -32622,8 +32798,28 @@ snapshots: msw: 2.15.0(@types/node@24.19.2)(typescript@6.0.3) vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1) + '@vitest/pretty-format@5.0.5': + dependencies: + tinyrainbow: 3.2.0 + '@vitest/spy@5.0.5': {} + '@vitest/ui@5.0.5(vitest@5.0.5)': + dependencies: + '@vitest/utils': 5.0.5 + fflate: 0.8.3 + flatted: 3.4.4 + pathe: 2.0.3 + sirv: 3.0.2 + tinyrainbow: 3.2.0 + vitest: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + + '@vitest/utils@5.0.5': + dependencies: + '@vitest/pretty-format': 5.0.5 + convert-source-map: 2.0.0 + tinyrainbow: 3.2.0 + '@volar/kit@2.4.28(typescript@6.0.3)': dependencies: '@volar/language-service': 2.4.28(typescript@6.0.3) @@ -35921,12 +36117,12 @@ snapshots: flat-cache@4.0.1: dependencies: - flatted: 3.4.2 + flatted: 3.4.4 keyv: 4.5.4 flat@5.0.2: {} - flatted@3.4.2: {} + flatted@3.4.4: {} flattie@1.1.1: {} @@ -40471,6 +40667,12 @@ snapshots: exsolve: 1.1.3 pathe: 2.0.3 + playwright-core@1.65.1: {} + + playwright@1.65.1: + dependencies: + playwright-core: 1.65.1 + plist@3.1.0: dependencies: '@xmldom/xmldom': 0.8.15 @@ -40481,6 +40683,8 @@ snapshots: pngjs@3.4.0: {} + pngjs@7.0.0: {} + possible-typed-array-names@1.1.0: {} postcss-calc@10.1.1(postcss@8.5.32): @@ -43518,7 +43722,7 @@ snapshots: optionalDependencies: vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1) - vitest@5.0.5(@types/node@24.19.2)(@vitest/coverage-istanbul@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)): + vitest@5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)): dependencies: '@types/chai': 5.2.3 '@vitest/mocker': 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) @@ -43536,13 +43740,15 @@ snapshots: why-is-node-running: 3.2.1 optionalDependencies: '@types/node': 24.19.2 + '@vitest/browser-playwright': 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(playwright@1.65.1)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(vitest@5.0.5) '@vitest/coverage-istanbul': 5.0.5(vitest@5.0.5) + '@vitest/ui': 5.0.5(vitest@5.0.5) jsdom: 27.4.0(supports-color@10.2.2) transitivePeerDependencies: - msw optional: true - vitest@5.0.5(@types/node@24.19.2)(@vitest/coverage-istanbul@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)): + vitest@5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)): dependencies: '@types/chai': 5.2.3 '@vitest/mocker': 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) @@ -43560,12 +43766,14 @@ snapshots: why-is-node-running: 3.2.1 optionalDependencies: '@types/node': 24.19.2 + '@vitest/browser-playwright': 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(playwright@1.65.1)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1))(vitest@5.0.5) '@vitest/coverage-istanbul': 5.0.5(vitest@5.0.5) + '@vitest/ui': 5.0.5(vitest@5.0.5) jsdom: 27.4.0(supports-color@10.2.2) transitivePeerDependencies: - msw - vitest@5.0.5(@types/node@24.19.2)(@vitest/coverage-istanbul@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)): + vitest@5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)): dependencies: '@types/chai': 5.2.3 '@vitest/mocker': 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) @@ -43583,7 +43791,9 @@ snapshots: why-is-node-running: 3.2.1 optionalDependencies: '@types/node': 24.19.2 + '@vitest/browser-playwright': 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(playwright@1.65.1)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(vitest@5.0.5) '@vitest/coverage-istanbul': 5.0.5(vitest@5.0.5) + '@vitest/ui': 5.0.5(vitest@5.0.5) jsdom: 27.4.0(supports-color@7.2.0) transitivePeerDependencies: - msw diff --git a/scripts/port-query-client-tests.mjs b/scripts/port-query-client-tests.mjs new file mode 100644 index 00000000000..f0c76c4d117 --- /dev/null +++ b/scripts/port-query-client-tests.mjs @@ -0,0 +1,180 @@ +// Port only calls on the original QueryClient. The upstream checker distinguishes +// its methods from identically named methods on observers, caches and promises. +import path from 'node:path' +import ts from 'typescript' + +const renamed = { + query: 'fetchQuery', + infiniteQuery: 'fetchInfiniteQuery', + mount: 'mountQueryClient', + unmount: 'unmountQueryClient', + clear: 'clearQueryClient', +} + +export function queryClientTestPort(upstream, files, packageName) { + const config = ts.readConfigFile( + path.join(upstream, 'tsconfig.json'), + ts.sys.readFile, + ) + const { options } = ts.parseJsonConfigFileContent( + config.config, + ts.sys, + upstream, + ) + const program = ts.createProgram(files, options) + const checker = program.getTypeChecker() + + function isClientMethod(receiver, name) { + return checker + .getTypeAtLocation(receiver) + .getProperty(name) + ?.declarations?.some( + (declaration) => + declaration.parent.name?.text === 'QueryClient' && + /\/query-core\/(?:src|build|dist-ts)\//.test( + declaration.getSourceFile().fileName, + ), + ) + } + + return function port(file) { + const source = program.getSourceFile(file) + const edits = [] + const api = '__clientOperations' + let usesOperations = false + let checksArguments = false + function edit(start, end, text) { + edits.push({ start, end, text }) + } + function operation(name) { + usesOperations = true + return api + '.' + (renamed[name] ?? name) + } + function typeReference(node) { + if ( + ts.isIndexedAccessTypeNode(node) && + ts.isLiteralTypeNode(node.indexType) && + ts.isStringLiteral(node.indexType.literal) && + isClientMethod(node.objectType, node.indexType.literal.text) + ) { + return { + operation: 'typeof ' + operation(node.indexType.literal.text), + client: api + '.QueryClient', + } + } + if ( + ts.isTypeQueryNode(node) && + ts.isQualifiedName(node.exprName) && + isClientMethod(node.exprName.left, node.exprName.right.text) + ) { + const generic = node.typeArguments?.length + ? '<' + + node.typeArguments.map((t) => t.getText(source)).join(', ') + + '>' + : '' + return { + operation: 'typeof ' + operation(node.exprName.right.text) + generic, + client: 'typeof ' + node.exprName.left.getText(source), + } + } + } + function visit(node) { + if ( + (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && + node.moduleSpecifier && + ts.isStringLiteral(node.moduleSpecifier) && + node.moduleSpecifier.text === '@tanstack/query-core' + ) { + edit( + node.moduleSpecifier.getStart(), + node.moduleSpecifier.end, + JSON.stringify(packageName), + ) + return + } + if ( + ts.isCallExpression(node) && + ts.isPropertyAccessExpression(node.expression) + ) { + const member = node.expression + if (isClientMethod(member.expression, member.name.text)) { + edit(member.getStart(), member.end, operation(member.name.text)) + edit( + node.arguments.pos, + node.arguments.pos, + member.expression.getText(source) + + (node.arguments.length ? ', ' : ''), + ) + for (const arg of [...(node.typeArguments ?? []), ...node.arguments]) + visit(arg) + return + } + } + // Tests that inspect the old parameter tuple still check every original + // argument. The new first argument must be compatible with the receiver. + if ( + ts.isTypeReferenceNode(node) && + node.typeName.getText(source) === 'Parameters' && + node.typeArguments?.length === 1 + ) { + const ref = typeReference(node.typeArguments[0]) + if (ref) { + checksArguments = true + edit( + node.getStart(), + node.end, + '__OperationArgs<' + ref.operation + ', ' + ref.client + '>', + ) + return + } + } + if ( + ts.isPropertyAccessExpression(node) && + node.name.text === 'parameters' && + ts.isCallExpression(node.expression) + ) { + const assertion = node.expression, + member = assertion.arguments[0] + if ( + assertion.expression.getText(source) === 'expectTypeOf' && + member && + ts.isPropertyAccessExpression(member) && + isClientMethod(member.expression, member.name.text) + ) { + checksArguments = true + edit( + node.getStart(), + node.end, + 'expectTypeOf<__OperationArgs>()', + ) + return + } + } + ts.forEachChild(node, visit) + } + visit(source) + let result = source.text + for (const { start, end, text } of edits.sort( + (a, b) => b.start - a.start || b.end - a.end, + )) { + result = result.slice(0, start) + text + result.slice(end) + } + if (!usesOperations) return result + const argumentsType = checksArguments + ? 'type __OperationArgs unknown, Client> = Parameters extends [Client, ...infer Args] ? Args : never\n' + : '' + return ( + 'import * as ' + + api + + ' from ' + + JSON.stringify(packageName) + + '\n' + + argumentsType + + result + ) + } +} diff --git a/scripts/port-query-projection-tests.mjs b/scripts/port-query-projection-tests.mjs new file mode 100644 index 00000000000..089d703beaf --- /dev/null +++ b/scripts/port-query-projection-tests.mjs @@ -0,0 +1,83 @@ +// Port explicitly marked query options in the copy used by the pluggable adapter. +// A tuple literal keeps inline callbacks contextually typed by the actual query hook. +import { readdirSync, readFileSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import ts from 'typescript' + +export function portProjectionOptions(directory) { + for (const file of readdirSync(directory, { withFileTypes: true })) { + const path = join(directory, file.name) + if (file.isDirectory()) { + portProjectionOptions(path) + continue + } + if (!/\.tsx?$/.test(file.name)) continue + const text = readFileSync(path, 'utf8') + if (!text.includes('@tanstack/query-test-utils/projection')) continue + + const source = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true) + const edits = [] + const imports = new Set() + function visit(node) { + if ( + (ts.isMethodDeclaration(node) || ts.isPropertyAssignment(node)) && + ts.isObjectLiteralExpression(node.parent) && + ts.isComputedPropertyName(node.name) && + ts.isIdentifier(node.name.expression) + ) { + const marker = node.name.expression.text + if (marker === 'selectOption' || marker === 'placeholderOption') { + const isSelect = marker === 'selectOption' + const feature = isSelect ? 'select' : 'placeholderData' + const name = isSelect ? '__querySelect' : '__queryPlaceholder' + const wrapper = isSelect ? 'portSelect' : 'portPlaceholder' + if (ts.isMethodDeclaration(node)) { + imports.add(feature + ' as ' + name) + edits.push([ + node.name.end, + node.name.end, + ': [' + name + ', function', + ]) + edits.push([node.end, node.end, ']']) + } else { + const input = node.initializer + if ( + (ts.isArrowFunction(input) || ts.isFunctionExpression(input)) && + input.parameters.some((parameter) => !parameter.type) + ) { + imports.add(feature + ' as ' + name) + edits.push([ + input.getStart(source), + input.getStart(source), + '[' + name + ', ', + ]) + edits.push([input.end, input.end, ']']) + } else if (input.getText(source) !== 'undefined') { + imports.add(wrapper) + edits.push([ + input.getStart(source), + input.getStart(source), + wrapper + '(', + ]) + edits.push([input.end, input.end, ')']) + } + } + } + } + ts.forEachChild(node, visit) + } + visit(source) + if (!edits.length) continue + let result = text + for (const [start, end, replacement] of edits.sort((a, b) => b[0] - a[0])) { + result = result.slice(0, start) + replacement + result.slice(end) + } + writeFileSync( + path, + 'import { ' + + [...imports].join(', ') + + " } from '@tanstack/query-test-utils/projection'\n" + + result, + ) + } +} diff --git a/scripts/react-query-compat.config.ts b/scripts/react-query-compat.config.ts new file mode 100644 index 00000000000..9f6f7ee8424 --- /dev/null +++ b/scripts/react-query-compat.config.ts @@ -0,0 +1,38 @@ +import { readFileSync } from 'node:fs' +import { basename, join, resolve } from 'node:path' +import { defineConfig } from 'vitest/config' +import core from '../packages/query-core/vite.config.ts' +import react from '../packages/react-query/vite.config.ts' + +const adapter = process.env.REACT_QUERY_COMPAT_ADAPTER! +const suite = basename(resolve(process.cwd(), '../..')) +const isReact = suite === 'react-query' + +const base = isReact ? react : core +const { paths } = JSON.parse(readFileSync('tsconfig.json', 'utf8')) + .compilerOptions as { paths: Record } + +export default defineConfig({ + ...base, + resolve: { + ...base.resolve, + // Use the same entry points for test execution and type checking. + alias: Object.fromEntries( + Object.entries(paths).map(([name, [file]]) => [name, file]), + ), + }, + test: { + ...base.test, + name: `${basename(adapter)}/${suite}`, + // Override the relative paths inherited from the upstream project. + setupFiles: isReact ? [resolve('test-setup.ts')] : [], + coverage: { + ...base.test?.coverage, + include: [ + join(adapter, isReact ? 'src/*.{ts,tsx}' : 'src/runtime/**/*.ts'), + ], + reportsDirectory: join(adapter, 'coverage', suite), + allowExternal: true, + }, + }, +}) diff --git a/scripts/test-react-query-compat.mjs b/scripts/test-react-query-compat.mjs new file mode 100644 index 00000000000..070160a3af4 --- /dev/null +++ b/scripts/test-react-query-compat.mjs @@ -0,0 +1,161 @@ +// Run the original runtime and type suites against the pluggable adapter. The temporary +// projects preserve the suites' relative imports without duplicating test cases. +import { execFileSync } from 'node:child_process' +import { + cpSync, + mkdirSync, + mkdtempSync, + readdirSync, + rmSync, + writeFileSync, +} from 'node:fs' +import { createRequire } from 'node:module' +import { basename, join, relative, resolve, sep } from 'node:path' +import { queryClientTestPort } from './port-query-client-tests.mjs' +import { portProjectionOptions } from './port-query-projection-tests.mjs' + +const adapter = process.cwd() +const repository = resolve(import.meta.dirname, '..') +const require = createRequire(import.meta.url) +const entry = join(adapter, 'src/index.ts') +const packageName = '@tanstack/react-query-pluggable' +const shared = [ + 'environmentManager', + 'focusManager', + 'onlineManager', + 'removable', + 'retryer', + 'subscribable', + 'timeoutManager', +] + +// Only adapt imports in copies of the upstream tests and their setup. The +// implementation and its workspace dependencies resolve the real core package. +function importPath(from, to) { + return './' + relative(from, to).split(sep).join('/') +} + +for (const suite of ['query-core', 'react-query']) { + const upstream = join(repository, 'packages', suite) + const cache = join(upstream, '.cache') + mkdirSync(cache, { recursive: true }) + const project = mkdtempSync(join(cache, 'compat-')) + try { + const source = join(project, 'src') + const implementation = + suite === 'query-core' + ? join(adapter, 'src/runtime') + : join(adapter, 'src') + cpSync(join(upstream, 'src/__tests__'), join(source, '__tests__'), { + recursive: true, + // Only query-core exposes the extension points for non-React adapters. + filter: (path) => + suite !== 'query-core' || basename(path) !== 'frameworkAdapters', + }) + const tests = join(source, '__tests__') + const originals = join(upstream, 'src/__tests__') + const testFiles = readdirSync(tests, { recursive: true }).filter((file) => + /\.tsx?$/.test(file), + ) + const configFiles = + suite === 'react-query' + ? [ + join(upstream, 'test-setup.ts'), + join( + repository, + 'packages/query-persist-client-core/src/createPersister.ts', + ), + ] + : [] + const port = queryClientTestPort( + upstream, + [...testFiles.map((file) => join(originals, file)), ...configFiles], + packageName, + ) + function copyTestModule(from, to) { + writeFileSync(to, port(from)) + } + for (const file of testFiles) + copyTestModule(join(originals, file), join(tests, file)) + portProjectionOptions(tests) + + for (const file of readdirSync(implementation, { withFileTypes: true })) { + if (!file.isFile() || !/\.tsx?$/.test(file.name)) continue + const target = importPath(source, join(implementation, file.name)) + writeFileSync(join(source, file.name), `export * from '${target}'\n`) + } + if (suite === 'query-core') { + for (const name of shared) { + writeFileSync( + join(source, name + '.ts'), + "export * from '@tanstack/query-core/primitives'\n", + ) + } + // The pluggable runtime exposes the page fetcher directly. + writeFileSync( + join(source, '__tests__/infiniteFetch.ts'), + `export { prepareInfiniteFetch } from '../infiniteQueryBehavior'\n`, + ) + // Upstream tests use ".." for the public package and "../foo" for internals. + writeFileSync( + join(source, 'index.ts'), + `export * from '${importPath(source, entry)}'\n`, + ) + } + + const setup = join(project, 'test-setup.ts') + const persister = join(source, 'createPersister.ts') + if (suite === 'react-query') { + copyTestModule(join(upstream, 'test-setup.ts'), setup) + copyTestModule( + join( + repository, + 'packages/query-persist-client-core/src/createPersister.ts', + ), + persister, + ) + } + const tsconfig = { + extends: join(adapter, 'tsconfig.json'), + compilerOptions: { + rootDir: repository, + composite: false, + incremental: false, + emitDeclarationOnly: false, + noEmit: true, + paths: { + [packageName]: [entry], + // This suite exercises only the per-query persistence implementation. + ...(suite === 'react-query' && { + '@tanstack/query-persist-client-core': [persister], + }), + ...Object.fromEntries( + ['polling', 'projection', 'scope'].map((name) => [ + `@tanstack/query-test-utils/${name}`, + [join(adapter, `tests/compat-${name}.ts`)], + ]), + ), + }, + }, + include: suite === 'react-query' ? ['src', setup] : ['src'], + } + writeFileSync(join(project, 'tsconfig.json'), JSON.stringify(tsconfig)) + execFileSync( + process.execPath, + [ + join(require.resolve('vitest/package.json'), '../vitest.mjs'), + 'run', + '--config', + join(import.meta.dirname, 'react-query-compat.config.ts'), + ...process.argv.slice(2), + ], + { + cwd: project, + stdio: 'inherit', + env: { ...process.env, REACT_QUERY_COMPAT_ADAPTER: adapter }, + }, + ) + } finally { + rmSync(project, { recursive: true, force: true }) + } +}