diff --git a/.changeset/treeshakable-query.md b/.changeset/treeshakable-query.md new file mode 100644 index 00000000000..63d6daddc8f --- /dev/null +++ b/.changeset/treeshakable-query.md @@ -0,0 +1,19 @@ +--- +'@tanstack/query-core': major +'@tanstack/react-query': major +'@tanstack/preact-query': major +'@tanstack/angular-query': major +'@tanstack/solid-query': major +'@tanstack/svelte-query': major +'@tanstack/vue-query': major +'@tanstack/lit-query': major +'@tanstack/query-broadcast-client-experimental': patch +'@tanstack/query-persist-client-core': patch +'@tanstack/query-devtools': patch +--- + +Make the ESM query core and its framework adapters treeshakable. Import client operations such as `query(client, options)`, `invalidateQueries(client, filters)`, and `getMutationCache(client)` from the adapter. A read-only client no longer needs to construct a mutation cache. + +In React and Preact, pass `queryOptions`, `suspenseQueryOptions`, `infiniteQueryOptions`, or `suspenseInfiniteQueryOptions` to `useQuery`. Import result checks such as `isSuccess(result)` to narrow data or errors. Use `useQueries` and `useSuspenseQueries` for a variable number of queries. + +Import `select`, `placeholderData`, `refetchInterval`, and `serialScope` where those features are used. Write `select: select((post) => post.title)` to project the observer's data while keeping the full post in the cache. Structural sharing remains enabled by default. Ordinary React and Preact queries can opt into boundaries with `throwOnError: [throwOnError, true]` or a predicate in the second position. diff --git a/.github/workflows/query-bundle-size.yml b/.github/workflows/query-bundle-size.yml new file mode 100644 index 00000000000..a8fd2f651cd --- /dev/null +++ b/.github/workflows/query-bundle-size.yml @@ -0,0 +1,113 @@ +name: TanStack Query bundle size + +on: + pull_request: + paths: + - '.github/workflows/query-bundle-size.yml' + - 'integrations/react/bundle-size/**' + - 'packages/query-core/**' + - 'packages/*-query/**' + - 'integrations/query/treeshaking/**' + - '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 v6 comparison baseline + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + # The v6 fixtures use the API from before the treeshakable changes. + ref: dc33f10cc5d7334a3b473fdf576b5d2aeb57ef4b + path: .cache/query-bundle-base + persist-credentials: false + - name: Install and build the baseline adapter + working-directory: .cache/query-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-treeshaking^...' run build + - name: Verify read-only imports across framework adapters + working-directory: integrations/query/treeshaking + run: | + pnpm run test:types + node check.ts > "$RUNNER_TEMP/query-readers.md" + - name: Type-check the benchmark and both adapters' screens + working-directory: integrations/react/bundle-size + run: | + pnpm run test:types + pnpm run check:baseline + - name: Build and measure production apps + id: measure + env: + QUERY_BASE_CHECKOUT: ${{ github.workspace }}/.cache/query-bundle-base + working-directory: integrations/react/bundle-size + run: | + pnpm run measure + echo >> dist/report.md + cat "$RUNNER_TEMP/query-readers.md" >> dist/report.md + 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/.size-limit.json b/.size-limit.json index c988ea32153..29589775464 100644 --- a/.size-limit.json +++ b/.size-limit.json @@ -2,14 +2,21 @@ { "name": "react full", "path": "packages/react-query/build/index.js", - "limit": "13.00 kB", + "limit": "13365 B", "ignore": ["react", "react-dom"] }, { "name": "react minimal", "path": "packages/react-query/build/index.js", "limit": "9.99 kB", - "import": "{ useQuery, QueryClient, QueryClientProvider }", + "import": "{ queryOptions, useQuery, QueryClient, QueryClientProvider }", + "ignore": ["react", "react-dom"] + }, + { + "name": "react paginated bookmarks", + "path": "packages/react-query/build/index.js", + "limit": "8196 B", + "import": "{ QueryClient, QueryClientProvider, queryOptions, useQuery, infiniteQueryOptions, isError, isFetching, isPending, mutationOptions, useMutation }", "ignore": ["react", "react-dom"] } ] diff --git a/docs/config.json b/docs/config.json index 065b61cc206..77553bbfe3d 100644 --- a/docs/config.json +++ b/docs/config.json @@ -386,6 +386,10 @@ { "label": "Migrating to v5", "to": "framework/react/guides/migrating-to-v5" + }, + { + "label": "Migrating to v6", + "to": "framework/react/guides/migrating-to-v6" } ] }, diff --git a/docs/eslint/prefer-query-options.md b/docs/eslint/prefer-query-options.md index 3228774bf7d..16b1596edb8 100644 --- a/docs/eslint/prefer-query-options.md +++ b/docs/eslint/prefer-query-options.md @@ -61,11 +61,16 @@ function getFooOptions(id) { } function useFooQuery(id) { - return useQuery({ ...getFooOptions(id), select: (data) => data.foo }) + return useQuery( + queryOptions({ + ...getFooOptions(id), + select: select((data) => data.foo), + }), + ) } ``` -The rule also enforces reusing `queryKey` from a `queryOptions` result instead of typing it manually in `QueryClient` methods or filters. +The rule also enforces reusing `queryKey` from a `queryOptions` result instead of typing it manually in client-first operations or filters. It recognizes named imports and aliases from TanStack Query. Examples of **incorrect** `queryKey` references for this rule: @@ -81,7 +86,7 @@ function todoOptions(id) { function Component({ id }) { const queryClient = useQueryClient() - return queryClient.getQueryData(['todo', id]) + return getQueryData(queryClient, ['todo', id]) } ``` @@ -97,7 +102,7 @@ function todoOptions(id) { function Component({ id }) { const queryClient = useQueryClient() - return queryClient.invalidateQueries({ queryKey: ['todo', id] }) + return invalidateQueries(queryClient, { queryKey: ['todo', id] }) } ``` @@ -115,7 +120,7 @@ function todoOptions(id) { function Component({ id }) { const queryClient = useQueryClient() - return queryClient.getQueryData(todoOptions(id).queryKey) + return getQueryData(queryClient, todoOptions(id).queryKey) } ``` @@ -131,7 +136,7 @@ function todoOptions(id) { function Component({ id }) { const queryClient = useQueryClient() - return queryClient.invalidateQueries({ queryKey: todoOptions(id).queryKey }) + return invalidateQueries(queryClient, { queryKey: todoOptions(id).queryKey }) } ``` diff --git a/docs/framework/angular/guides/infinite-queries.md b/docs/framework/angular/guides/infinite-queries.md index b912fb41470..9ec9abfa1ad 100644 --- a/docs/framework/angular/guides/infinite-queries.md +++ b/docs/framework/angular/guides/infinite-queries.md @@ -112,14 +112,20 @@ projectsQuery = injectInfiniteQuery(() => ({ [//]: # 'Example4' ```ts -projectsQuery = injectInfiniteQuery(() => ({ - queryKey: ['projects'], - queryFn: fetchProjects, - select: (data) => ({ - pages: [...data.pages].reverse(), - pageParams: [...data.pageParams].reverse(), +import { infiniteQueryOptions, select } from '@tanstack/angular-query' + +projectsQuery = injectInfiniteQuery(() => + infiniteQueryOptions({ + queryKey: ['projects'], + queryFn: fetchProjects, + initialPageParam: 0, + getNextPageParam: (lastPage) => lastPage.nextCursor, + select: select((data) => ({ + pages: [...data.pages].reverse(), + pageParams: [...data.pageParams].reverse(), + })), }), -})) +) ``` [//]: # 'Example4' diff --git a/docs/framework/angular/guides/polling.md b/docs/framework/angular/guides/polling.md index 38e9b8a0b11..9fa041d3444 100644 --- a/docs/framework/angular/guides/polling.md +++ b/docs/framework/angular/guides/polling.md @@ -8,10 +8,12 @@ replace: { '@tanstack/react-query': '@tanstack/angular-query' } [//]: # 'Example1' ```ts +import { refetchInterval } from '@tanstack/angular-query' + injectQuery(() => ({ queryKey: ['prices'], queryFn: fetchPrices, - refetchInterval: 5 * 1000, // every 5 seconds + refetchInterval: refetchInterval(5 * 1000), // every 5 seconds })) ``` @@ -19,17 +21,19 @@ injectQuery(() => ({ [//]: # 'Example2' ```ts +import { refetchInterval } from '@tanstack/angular-query' + injectQuery(() => { const jobId = this.jobId() return { queryKey: ['job', jobId], queryFn: () => fetchJobStatus(jobId), - refetchInterval: (query) => { + refetchInterval: refetchInterval((query) => { // Stop polling once the job finishes if (query.state.data?.status === 'complete') return false return 2 * 1000 - }, + }), } }) ``` @@ -38,10 +42,12 @@ injectQuery(() => { [//]: # 'Example3' ```ts +import { refetchInterval } from '@tanstack/angular-query' + injectQuery(() => ({ queryKey: ['portfolio'], queryFn: fetchPortfolio, - refetchInterval: 30 * 1000, + refetchInterval: refetchInterval(30 * 1000), refetchIntervalInBackground: true, })) ``` @@ -50,6 +56,8 @@ injectQuery(() => ({ [//]: # 'Example4' ```ts +import { refetchInterval } from '@tanstack/angular-query' + injectQuery(() => { // Read signals here so the query reacts when they change const tokenAddress = this.tokenAddress() @@ -58,10 +66,10 @@ injectQuery(() => { return { queryKey: ['prices', tokenAddress], queryFn: () => fetchPrice(tokenAddress), - refetchInterval: () => { + refetchInterval: refetchInterval(() => { if (!tokenAddress || isPaused) return false return 15 * 1000 - }, + }), } }) ``` @@ -70,10 +78,12 @@ injectQuery(() => { [//]: # 'Example5' ```ts +import { refetchInterval } from '@tanstack/angular-query' + injectQuery(() => ({ queryKey: ['chainStatus'], queryFn: fetchChainStatus, - refetchInterval: 10 * 1000, + refetchInterval: refetchInterval(10 * 1000), networkMode: 'always', })) ``` diff --git a/docs/framework/angular/guides/query-options.md b/docs/framework/angular/guides/query-options.md index 691b52ec4fd..e833501ea6f 100644 --- a/docs/framework/angular/guides/query-options.md +++ b/docs/framework/angular/guides/query-options.md @@ -7,7 +7,12 @@ ref: docs/framework/react/guides/query-options.md [//]: # 'Example1' ```ts -import { noop, queryOptions } from '@tanstack/angular-query' +import { + noop, + query, + queryOptions, + setQueryData, +} from '@tanstack/angular-query' @Injectable({ providedIn: 'root', @@ -38,21 +43,25 @@ queries = inject(QueriesService) postQuery = injectQuery(() => this.queries.post(this.postId())) -void queryClient.query(this.queries.post(23)).catch(noop) -queryClient.setQueryData(this.queries.post(42).queryKey, newPost) +void query(queryClient, this.queries.post(23)).catch(noop) +setQueryData(queryClient, this.queries.post(42).queryKey, newPost) ``` [//]: # 'Example1' [//]: # 'Example2' ```ts +import { queryOptions, select } from '@tanstack/angular-query' + // Type inference still works, so postQuery.data will be the return type of select instead of queryFn queries = inject(QueriesService) -postQuery = injectQuery(() => ({ - ...this.queries.post(1), - select: (data) => data.title, -})) +postQuery = injectQuery(() => + queryOptions({ + ...this.queries.post(1), + select: select((data) => data.title), + }), +) ``` [//]: # 'Example2' diff --git a/docs/framework/angular/typescript.md b/docs/framework/angular/typescript.md index ffacb78c1c1..7ba7502b8c4 100644 --- a/docs/framework/angular/typescript.md +++ b/docs/framework/angular/typescript.md @@ -37,17 +37,21 @@ class MyComponent { [//]: # 'TypeInference2' ```angular-ts +import { queryOptions, select } from '@tanstack/angular-query' + @Component({ // ... template: `@let data = query.data();`, // ^? data: string | undefined }) class MyComponent { - query = injectQuery(() => ({ - queryKey: ['test'], - queryFn: () => Promise.resolve(5), - select: (data) => data.toString(), - })) + query = injectQuery(() => + queryOptions({ + queryKey: ['test'], + queryFn: () => Promise.resolve(5), + select: select((data) => data.toString()), + }), + ) } ``` diff --git a/docs/framework/preact/guides/infinite-queries.md b/docs/framework/preact/guides/infinite-queries.md index 77a6f6934f9..b502b2e54fb 100644 --- a/docs/framework/preact/guides/infinite-queries.md +++ b/docs/framework/preact/guides/infinite-queries.md @@ -8,7 +8,12 @@ replace: { 'react-query': 'preact-query', 'React': 'Preact' } [//]: # 'Example' ```tsx -import { useInfiniteQuery } from '@tanstack/preact-query' +import { + useQuery, + infiniteQueryOptions, + isFetching, + isFetchingNextPage, +} from '@tanstack/preact-query' function Projects() { const fetchProjects = async ({ pageParam }) => { @@ -16,28 +21,22 @@ function Projects() { return res.json() } - const { - data, - error, - fetchNextPage, - hasNextPage, - isFetching, - isFetchingNextPage, - status, - } = useInfiniteQuery({ - queryKey: ['projects'], - queryFn: fetchProjects, - initialPageParam: 0, - getNextPageParam: (lastPage, pages) => lastPage.nextCursor, - }) + const infiniteQueryResult = useQuery( + infiniteQueryOptions({ + queryKey: ['projects'], + queryFn: fetchProjects, + initialPageParam: 0, + getNextPageParam: (lastPage, pages) => lastPage.nextCursor, + }), + ) - return status === 'pending' ? ( + return infiniteQueryResult.status === 'pending' ? (

Loading...

- ) : status === 'error' ? ( -

Error: {error.message}

+ ) : infiniteQueryResult.status === 'error' ? ( +

Error: {infiniteQueryResult.error.message}

) : ( <> - {data.pages.map((group, i) => ( + {infiniteQueryResult.data.pages.map((group, i) => (
{group.data.map((project) => (

{project.name}

@@ -46,17 +45,24 @@ function Projects() { ))}
-
{isFetching && !isFetchingNextPage ? 'Fetching...' : null}
+
+ {isFetching(infiniteQueryResult) && + !isFetchingNextPage(infiniteQueryResult) + ? 'Fetching...' + : null} +
) } diff --git a/docs/framework/preact/quick-start.md b/docs/framework/preact/quick-start.md index 9f84f255255..178cc517937 100644 --- a/docs/framework/preact/quick-start.md +++ b/docs/framework/preact/quick-start.md @@ -11,6 +11,8 @@ If you're looking for a fully functioning example, please have a look at our [si ```tsx import { + invalidateQueries, + queryOptions, useQuery, useMutation, useQueryClient, @@ -37,14 +39,16 @@ function Todos() { const queryClient = useQueryClient() // Queries - const query = useQuery({ queryKey: ['todos'], queryFn: getTodos }) + const query = useQuery( + queryOptions({ queryKey: ['todos'], queryFn: getTodos }), + ) // Mutations const mutation = useMutation({ mutationFn: postTodo, onSuccess: () => { // Invalidate and refetch - queryClient.invalidateQueries({ queryKey: ['todos'] }) + return invalidateQueries(queryClient, { queryKey: ['todos'] }) }, }) diff --git a/docs/framework/react/comparison.md b/docs/framework/react/comparison.md index a0b307a2867..ddb254c295a 100644 --- a/docs/framework/react/comparison.md +++ b/docs/framework/react/comparison.md @@ -69,7 +69,7 @@ Feature/Capability Key: > **3 Partial query matching** - Because React Query uses deterministic query key serialization, this allows you to manipulate variable groups of queries without having to know each individual query-key that you want to match, eg. you can refetch every query that starts with `todos` in its key, regardless of variables, or you can target specific queries with (or without) variables or nested properties, and even use a filter function to only match queries that pass your specific conditions. -> **4 Pre-usage Query Configuration** - This is simply a fancy name for being able to configure how queries and mutations will behave before they are used. For instance, a query can be fully configured with defaults beforehand and when the time comes to use it, `useQuery({ queryKey, queryFn: defaultQueryFn })` is sufficient, instead of being required to pass the fetcher and/or options with every usage. SWR does have a partial form of this feature by allowing you to pre-configure a default fetcher, but only as a global fetcher, not on a per-query basis and definitely not for mutations. +> **4 Pre-usage Query Configuration** - This is simply a fancy name for being able to configure how queries and mutations will behave before they are used. For instance, a query can be fully configured with defaults beforehand and when the time comes to use it, `useQuery(queryOptions({ queryKey, queryFn: defaultQueryFn }))` is sufficient, instead of being required to pass the fetcher and/or options with every usage. SWR does have a partial form of this feature by allowing you to pre-configure a default fetcher, but only as a global fetcher, not on a per-query basis and definitely not for mutations. > **5 Automatic Refetch after Mutation** - For truly automatic refetching to happen after a mutation occurs, a schema is necessary (like the one graphQL provides) along with heuristics that help the library know how to identify individual entities and entities types in that schema. diff --git a/docs/framework/react/graphql.md b/docs/framework/react/graphql.md index d3737db21b6..d52d1dad883 100644 --- a/docs/framework/react/graphql.md +++ b/docs/framework/react/graphql.md @@ -14,7 +14,7 @@ Because React Query's fetching mechanisms are agnostically built on Promises, yo React Query, used in combination with `graphql-request^5` and [GraphQL Code Generator](https://graphql-code-generator.com/) provides full-typed GraphQL operations: ```tsx -import { useQuery } from '@tanstack/react-query' +import { useQuery, queryOptions } from '@tanstack/react-query' import request from 'graphql-request' import { graphql } from './gql/gql' @@ -33,16 +33,18 @@ const allFilmsWithVariablesQueryDocument = graphql(/* GraphQL */ ` function App() { // `data` is fully typed! - const { data } = useQuery({ - queryKey: ['films'], - queryFn: async () => - request( - 'https://swapi-graphql.netlify.app/.netlify/functions/index', - allFilmsWithVariablesQueryDocument, - // variables are type-checked too! - { first: 10 }, - ), - }) + const { data } = useQuery( + queryOptions({ + queryKey: ['films'], + queryFn: async () => + request( + 'https://swapi-graphql.netlify.app/.netlify/functions/index', + allFilmsWithVariablesQueryDocument, + // variables are type-checked too! + { first: 10 }, + ), + }), + ) // ... } ``` diff --git a/docs/framework/react/guides/advanced-ssr.md b/docs/framework/react/guides/advanced-ssr.md index 208555cd710..52f6f85665a 100644 --- a/docs/framework/react/guides/advanced-ssr.md +++ b/docs/framework/react/guides/advanced-ssr.md @@ -110,18 +110,18 @@ import { HydrationBoundary, QueryClient, useQuery, + query, + queryOptions, } from '@tanstack/react-query' // This could also be getServerSideProps export async function getStaticProps() { const queryClient = new QueryClient() - await queryClient - .query({ - queryKey: ['posts'], - queryFn: getPosts, - }) - .catch(noop) + await query(queryClient, { + queryKey: ['posts'], + queryFn: getPosts, + }).catch(noop) return { props: { @@ -134,19 +134,23 @@ function Posts() { // This useQuery could just as well happen in some deeper child to // the , data will be available immediately either way // - // Note that we are using useQuery here instead of useSuspenseQuery. + // Note that we are passing regular queryOptions to useQuery here. // Because this data has already been prefetched, there is no need to // ever suspend in the component itself. If we forget or remove the // prefetch, this will instead fetch the data on the client, while - // using useSuspenseQuery would have had worse side effects. - const { data } = useQuery({ queryKey: ['posts'], queryFn: getPosts }) + // suspending during the client render would change that behavior. + const { data } = useQuery( + queryOptions({ queryKey: ['posts'], queryFn: getPosts }), + ) // This query was not prefetched on the server and will not start // fetching until on the client, both patterns are fine to mix - const { data: commentsData } = useQuery({ - queryKey: ['posts-comments'], - queryFn: getComments, - }) + const { data: commentsData } = useQuery( + queryOptions({ + queryKey: ['posts-comments'], + queryFn: getComments, + }), + ) // ... } @@ -168,18 +172,17 @@ import { dehydrate, HydrationBoundary, QueryClient, + query, } from '@tanstack/react-query' import Posts from './posts' export default async function PostsPage() { const queryClient = new QueryClient() - await queryClient - .query({ - queryKey: ['posts'], - queryFn: getPosts, - }) - .catch(noop) + await query(queryClient, { + queryKey: ['posts'], + queryFn: getPosts, + }).catch(noop) return ( // Neat! Serialization is now as easy as passing props. @@ -200,17 +203,21 @@ Next, we'll look at what the Client Component part looks like: export default function Posts() { // This useQuery could just as well happen in some deeper // child to , data will be available immediately either way - const { data } = useQuery({ - queryKey: ['posts'], - queryFn: () => getPosts(), - }) + const { data } = useQuery( + queryOptions({ + queryKey: ['posts'], + queryFn: () => getPosts(), + }), + ) // This query was not prefetched on the server and will not start // fetching until on the client, both patterns are fine to mix. - const { data: commentsData } = useQuery({ - queryKey: ['posts-comments'], - queryFn: getComments, - }) + const { data: commentsData } = useQuery( + queryOptions({ + queryKey: ['posts-comments'], + queryFn: getComments, + }), + ) // ... } @@ -234,6 +241,7 @@ import { dehydrate, HydrationBoundary, QueryClient, + query, } from '@tanstack/react-query' import CommentsServerComponent from './comments-server' import Posts from './posts' @@ -241,12 +249,10 @@ import Posts from './posts' export default async function PostsPage() { const queryClient = new QueryClient() - await queryClient - .query({ - queryKey: ['posts'], - queryFn: getPosts, - }) - .catch(noop) + await query(queryClient, { + queryKey: ['posts'], + queryFn: getPosts, + }).catch(noop) return ( @@ -267,12 +273,10 @@ import Comments from './comments' export default async function CommentsServerComponent() { const queryClient = new QueryClient() - await queryClient - .query({ - queryKey: ['posts-comments'], - queryFn: getComments, - }) - .catch(noop) + await query(queryClient, { + queryKey: ['posts-comments'], + queryFn: getComments, + }).catch(noop) return ( @@ -327,6 +331,7 @@ import { dehydrate, HydrationBoundary, QueryClient, + query, } from '@tanstack/react-query' import Posts from './posts' @@ -334,7 +339,7 @@ export default async function PostsPage() { const queryClient = new QueryClient() // Note we are getting the result from query - const posts = await queryClient.query({ + const posts = await query(queryClient, { queryKey: ['posts'], queryFn: getPosts, }) @@ -363,7 +368,7 @@ Using React Query with Server Components makes most sense if: It's hard to give general advice on when it makes sense to pair React Query with Server Components and not. **If you are just starting out with a new Server Components app, we suggest you start out with any tools for data fetching your framework provides you with and avoid bringing in React Query until you actually need it.** This might be never, and that's fine, use the right tool for the job! -If you do use it, a good rule of thumb is to avoid rendering the result of `queryClient.query` on the server or passing it to another component, even a Client Component one. +If you do use it, a good rule of thumb is to avoid rendering the result of `query` on the server or passing it to another component, even a Client Component one. From the React Query perspective, treat Server Components as a place to prefetch data, nothing more. @@ -436,7 +441,7 @@ Then, all we need to do is provide a `HydrationBoundary`, but we don't need to ` ```tsx // app/posts/page.tsx -import { dehydrate, HydrationBoundary } from '@tanstack/react-query' +import { dehydrate, HydrationBoundary, query } from '@tanstack/react-query' import { getQueryClient } from './get-query-client' import Posts from './posts' @@ -445,12 +450,10 @@ export default function PostsPage() { const queryClient = getQueryClient() // look ma, no await - void queryClient - .query({ - queryKey: ['posts'], - queryFn: getPosts, - }) - .catch(noop) + void query(queryClient, { + queryKey: ['posts'], + queryFn: getPosts, + }).catch(noop) return ( @@ -460,20 +463,22 @@ export default function PostsPage() { } ``` -On the client, the Promise will be put into the QueryCache for us. That means we can now call `useSuspenseQuery` inside the `Posts` component to "use" that Promise (which was created on the Server): +On the client, the Promise will be put into the QueryCache for us. That means we can now call `useQuery(suspenseQueryOptions(...))` inside the `Posts` component to "use" that Promise (which was created on the Server): ```tsx // app/posts/posts.tsx 'use client' export default function Posts() { - const { data } = useSuspenseQuery({ queryKey: ['posts'], queryFn: getPosts }) + const { data } = useQuery( + suspenseQueryOptions({ queryKey: ['posts'], queryFn: getPosts }), + ) // ... } ``` -> Note that you could also `useQuery` instead of `useSuspenseQuery`, and the Promise would still be picked up correctly. However, NextJs won't suspend in that case and the component will render in the `pending` status, which also opts out of server rendering the content. +> Note that you could also pass `queryOptions` to `useQuery`, and the Promise would still be picked up correctly. However, NextJs won't suspend in that case and the component will render in the `pending` status, which also opts out of server rendering the content. If you're using non-JSON data types and serialize the query results on the server, you can specify the `dehydrate.serializeData` and `hydrate.deserializeData` options to serialize and deserialize the data on each side of the boundary to ensure the data in the cache is the same format both on the server and the client: @@ -505,6 +510,7 @@ import { dehydrate, HydrationBoundary, QueryClient, + query, } from '@tanstack/react-query' import { getQueryClient } from './get-query-client' import Posts from './posts' @@ -514,12 +520,10 @@ export default function PostsPage() { const queryClient = getQueryClient() // look ma, no await - void queryClient - .query({ - queryKey: ['posts'], - queryFn: () => getPosts().then(serialize), // <-- serialize the data on the server - }) - .catch(noop) + void query(queryClient, { + queryKey: ['posts'], + queryFn: () => getPosts().then(serialize), // <-- serialize the data on the server + }).catch(noop) return ( @@ -534,7 +538,9 @@ export default function PostsPage() { 'use client' export default function Posts() { - const { data } = useSuspenseQuery({ queryKey: ['posts'], queryFn: getPosts }) + const { data } = useQuery( + suspenseQueryOptions({ queryKey: ['posts'], queryFn: getPosts }), + ) // ... } @@ -567,7 +573,7 @@ This ensures that only successfully resolved queries are persisted to storage, p While we recommend the prefetching solution detailed above because it flattens request waterfalls both on the initial page load **and** any subsequent page navigation, there is an experimental way to skip prefetching altogether and still have streaming SSR work: `@tanstack/react-query-next-experimental` -This package will allow you to fetch data on the server (in a Client Component) by just calling `useSuspenseQuery` in your component. Results will then be streamed from the server to the client as SuspenseBoundaries resolve. If you call `useSuspenseQuery` without wrapping it in a `` boundary, the HTML response won't start until the fetch resolves. This can be what you want depending on the situation, but keep in mind that this will hurt your TTFB. +This package will allow you to fetch data on the server (in a Client Component) by calling `useQuery` with `suspenseQueryOptions` in your component. Results will then be streamed from the server to the client as SuspenseBoundaries resolve. If you render the query without wrapping the component in a `` boundary, the HTML response won't start until the fetch resolves. This can be what you want depending on the situation, but keep in mind that this will hurt your TTFB. To achieve this, wrap your app in the `ReactQueryStreamedHydration` component: diff --git a/docs/framework/react/guides/background-fetching-indicators.md b/docs/framework/react/guides/background-fetching-indicators.md index 23d5b50f868..4b1f7a31db7 100644 --- a/docs/framework/react/guides/background-fetching-indicators.md +++ b/docs/framework/react/guides/background-fetching-indicators.md @@ -3,32 +3,29 @@ id: background-fetching-indicators title: Background Fetching Indicators --- -A query's `status === 'pending'` state is sufficient enough to show the initial hard-loading state for a query, but sometimes you may want to display an additional indicator that a query is refetching in the background. To do this, queries also supply you with an `isFetching` boolean that you can use to show that it's in a fetching state, regardless of the state of the `status` variable: +A query's `status === 'pending'` state is sufficient enough to show the initial hard-loading state for a query, but sometimes you may want to display an additional indicator that a query is refetching in the background. To do this, call `isFetching(result)` to check whether a fetch is in progress, regardless of the state of the `status` variable: [//]: # 'Example' ```tsx function Todos() { - const { - status, - data: todos, - error, - isFetching, - } = useQuery({ - queryKey: ['todos'], - queryFn: fetchTodos, - }) - - return status === 'pending' ? ( + const queryResult = useQuery( + queryOptions({ + queryKey: ['todos'], + queryFn: fetchTodos, + }), + ) + + return queryResult.status === 'pending' ? ( Loading... - ) : status === 'error' ? ( - Error: {error.message} + ) : queryResult.status === 'error' ? ( + Error: {queryResult.error.message} ) : ( <> - {isFetching ?
Refreshing...
: null} + {isFetching(queryResult) ?
Refreshing...
: null}
- {todos.map((todo) => ( + {queryResult.data.map((todo) => ( ))}
diff --git a/docs/framework/react/guides/caching.md b/docs/framework/react/guides/caching.md index bd76a1b7195..10ddc435746 100644 --- a/docs/framework/react/guides/caching.md +++ b/docs/framework/react/guides/caching.md @@ -14,20 +14,20 @@ This caching example illustrates the story and lifecycle of: - Inactive Queries - Garbage Collection -Let's assume we are using the default `gcTime` of **5 minutes** and the default `staleTime` of `0`. +Define `todos = queryOptions({ queryKey: ['todos'], queryFn: fetchTodos })`. This example uses the default `gcTime` of **5 minutes** and the default `staleTime` of `0`. -- A new instance of `useQuery({ queryKey: ['todos'], queryFn: fetchTodos })` mounts. +- A new instance of `useQuery(todos)` mounts. - Since no other queries have been made with the `['todos']` query key, this query will show a hard loading state and make a network request to fetch the data. - When the network request has completed, the returned data will be cached under the `['todos']` key. - The data will be marked as stale after the configured `staleTime` (defaults to `0`, or immediately). -- A second instance of `useQuery({ queryKey: ['todos'], queryFn: fetchTodos })` mounts elsewhere. +- A second instance of `useQuery(todos)` mounts elsewhere. - Since the cache already has data for the `['todos']` key from the first query, that data is immediately returned from the cache. - The new instance triggers a new network request using its query function. - Note that regardless of whether both `fetchTodos` query functions are identical or not, both queries' [`status`](../reference/functions/useQuery.md) are updated (including `isFetching`, `isPending`, and other related values) because they have the same query key. - When the request completes successfully, the cache's data under the `['todos']` key is updated with the new data, and both instances are updated with the new data. -- Both instances of the `useQuery({ queryKey: ['todos'], queryFn: fetchTodos })` query are unmounted and no longer in use. +- Both instances of the `useQuery(todos)` query are unmounted and no longer in use. - Since there are no more active instances of this query, a garbage collection timeout is set using `gcTime` to delete and garbage collect the query (defaults to **5 minutes**). -- Before the cache timeout (gcTime) has completed, another instance of `useQuery({ queryKey: ['todos'], queryFn: fetchTodos })` mounts. The query immediately returns the available cached data while the `fetchTodos` function is being run in the background. When it completes successfully, it will populate the cache with fresh data. -- The final instance of `useQuery({ queryKey: ['todos'], queryFn: fetchTodos })` unmounts. -- No more instances of `useQuery({ queryKey: ['todos'], queryFn: fetchTodos })` appear within **5 minutes**. +- Before the cache timeout (gcTime) has completed, another instance of `useQuery(todos)` mounts. The query immediately returns the available cached data while the `fetchTodos` function is being run in the background. When it completes successfully, it will populate the cache with fresh data. +- The final instance of `useQuery(todos)` unmounts. +- No more instances of `useQuery(todos)` appear within **5 minutes**. - The cached data under the `['todos']` key is deleted and garbage collected. diff --git a/docs/framework/react/guides/default-query-function.md b/docs/framework/react/guides/default-query-function.md index 01722cdd1c6..dd0ddc727b1 100644 --- a/docs/framework/react/guides/default-query-function.md +++ b/docs/framework/react/guides/default-query-function.md @@ -8,7 +8,13 @@ Set a default query function on the client to share it across queries. Pass `que [//]: # 'Example' ```tsx -import { defaultQueryFn } from '@tanstack/react-query' +import { + QueryClient, + QueryClientProvider, + defaultQueryFn, + queryOptions, + useQuery, +} from '@tanstack/react-query' // Define a default query function that will receive the query key const fetchByQueryKey = async ({ queryKey }) => { @@ -36,20 +42,24 @@ function App() { } function Posts() { - const { status, data, error, isFetching } = useQuery({ - queryKey: ['/posts'], - queryFn: defaultQueryFn, - }) + const posts = useQuery( + queryOptions({ + queryKey: ['/posts'], + queryFn: defaultQueryFn, + }), + ) // ... } function Post({ postId }) { - const { status, data, error, isFetching } = useQuery({ - queryKey: [`/posts/${postId}`], - queryFn: defaultQueryFn, - enabled: !!postId, - }) + const post = useQuery( + queryOptions({ + queryKey: [`/posts/${postId}`], + queryFn: defaultQueryFn, + enabled: !!postId, + }), + ) // ... } @@ -57,4 +67,4 @@ function Post({ postId }) { [//]: # 'Example' -Pass your own function as `queryFn` to override the client defaults. To configure a default function for specific query keys, use `queryClient.setQueryDefaults`. +Pass your own function as `queryFn` to override the client defaults. To configure a default function for specific query keys, use `setQueryDefaults`. diff --git a/docs/framework/react/guides/dependent-queries.md b/docs/framework/react/guides/dependent-queries.md index c2920012fcb..1cb0081b329 100644 --- a/docs/framework/react/guides/dependent-queries.md +++ b/docs/framework/react/guides/dependent-queries.md @@ -11,10 +11,12 @@ Dependent (or serial) queries depend on previous ones to finish before they can ```tsx // Get the user -const { data: user } = useQuery({ - queryKey: ['user', email], - queryFn: getUserByEmail, -}) +const { data: user } = useQuery( + queryOptions({ + queryKey: ['user', email], + queryFn: getUserByEmail, + }), +) const userId = user?.id @@ -23,12 +25,14 @@ const { status, fetchStatus, data: projects, -} = useQuery({ - queryKey: ['projects', userId], - queryFn: getProjectsByUser, - // The query will not execute until the userId exists - enabled: !!userId, -}) +} = useQuery( + queryOptions({ + queryKey: ['projects', userId], + queryFn: getProjectsByUser, + // The query will not execute until the userId exists + enabled: !!userId, + }), +) ``` [//]: # 'Example' @@ -37,7 +41,6 @@ The `projects` query will start in: ```tsx status: 'pending' -isPending: true fetchStatus: 'idle' ``` @@ -45,7 +48,6 @@ As soon as the `user` is available, the `projects` query will be `enabled` and w ```tsx status: 'pending' -isPending: true fetchStatus: 'fetching' ``` @@ -53,7 +55,6 @@ Once we have the projects, it will go to: ```tsx status: 'success' -isPending: false fetchStatus: 'idle' ``` @@ -65,11 +66,13 @@ Dynamic parallel query - `useQueries` can depend on a previous query also, here' ```tsx // Get the users ids -const { data: userIds } = useQuery({ - queryKey: ['users'], - queryFn: getUsersData, - select: (users) => users.map((user) => user.id), -}) +const { data: userIds } = useQuery( + queryOptions({ + queryKey: ['users'], + queryFn: getUsersData, + select: select((users) => users.map((user) => user.id)), + }), +) // Then get the users messages const usersMessages = useQueries({ diff --git a/docs/framework/react/guides/disabling-queries.md b/docs/framework/react/guides/disabling-queries.md index 891efdfe162..d265be3f4a8 100644 --- a/docs/framework/react/guides/disabling-queries.md +++ b/docs/framework/react/guides/disabling-queries.md @@ -20,31 +20,33 @@ When `enabled` is `false`: ```tsx function Todos() { - const { isLoading, isError, data, error, refetch, isFetching } = useQuery({ - queryKey: ['todos'], - queryFn: fetchTodoList, - enabled: false, - }) + const queryResult = useQuery( + queryOptions({ + queryKey: ['todos'], + queryFn: fetchTodoList, + enabled: false, + }), + ) return (
- + - {data ? ( + {queryResult.data ? (
    - {data.map((todo) => ( + {queryResult.data.map((todo) => (
  • {todo.title}
  • ))}
- ) : isError ? ( - Error: {error.message} - ) : isLoading ? ( + ) : isError(queryResult) ? ( + Error: {queryResult.error.message} + ) : isLoading(queryResult) ? ( Loading... ) : ( Not ready ... )} -
{isFetching ? 'Fetching...' : null}
+
{isFetching(queryResult) ? 'Fetching...' : null}
) } @@ -64,12 +66,14 @@ The enabled option can not only be used to permanently disable a query, but also function Todos() { const [filter, setFilter] = React.useState('') - const { data } = useQuery({ - queryKey: ['todos', filter], - queryFn: () => fetchTodos(filter), - // ⬇️ disabled as long as the filter is empty - enabled: !!filter, - }) + const { data } = useQuery( + queryOptions({ + queryKey: ['todos', filter], + queryFn: () => fetchTodos(filter), + // ⬇️ disabled as long as the filter is empty + enabled: !!filter, + }), + ) return (
@@ -87,9 +91,9 @@ function Todos() { Lazy queries will be in `status: 'pending'` right from the start because `pending` means that there is no data yet. This is technically true, however, since we are not currently fetching any data (as the query is not _enabled_), it also means you likely cannot use this flag to show a loading spinner. -If you are using disabled or lazy queries, you can use the `isLoading` flag instead. It's a derived flag that is computed from: +If you are using disabled or lazy queries, you can call `isLoading(result)`. It returns the same value as -`isPending && isFetching` +`isPending(result) && isFetching(result)`. so it will only be true if the query is currently fetching for the first time. @@ -102,16 +106,18 @@ If you are using TypeScript, you can use the `skipToken` to disable a query. Thi [//]: # 'Example3' ```tsx -import { skipToken, useQuery } from '@tanstack/react-query' +import { skipToken, useQuery, queryOptions } from '@tanstack/react-query' function Todos() { const [filter, setFilter] = React.useState() - const { data } = useQuery({ - queryKey: ['todos', filter], - // ⬇️ disabled as long as the filter is undefined or empty - queryFn: filter ? () => fetchTodos(filter) : skipToken, - }) + const { data } = useQuery( + queryOptions({ + queryKey: ['todos', filter], + // ⬇️ disabled as long as the filter is undefined or empty + queryFn: filter ? () => fetchTodos(filter) : skipToken, + }), + ) return (
diff --git a/docs/framework/react/guides/filters.md b/docs/framework/react/guides/filters.md index e290c430f58..efdd0c24d4a 100644 --- a/docs/framework/react/guides/filters.md +++ b/docs/framework/react/guides/filters.md @@ -11,16 +11,16 @@ A query filter is an object with certain conditions to match a query with: ```tsx // Cancel all queries -await queryClient.cancelQueries() +await cancelQueries(queryClient) // Remove all inactive queries that begin with `posts` in the key -queryClient.removeQueries({ queryKey: ['posts'], type: 'inactive' }) +removeQueries(queryClient, { queryKey: ['posts'], type: 'inactive' }) // Refetch all active queries -await queryClient.refetchQueries({ type: 'active' }) +await refetchQueries(queryClient, { type: 'active' }) // Refetch all active queries that begin with `posts` in the key -await queryClient.refetchQueries({ queryKey: ['posts'], type: 'active' }) +await refetchQueries(queryClient, { queryKey: ['posts'], type: 'active' }) ``` A query filter object supports the following properties: @@ -49,13 +49,13 @@ A mutation filter is an object with certain conditions to match a mutation with: ```tsx // Get the number of all fetching mutations -await queryClient.isMutating() +await isMutating(queryClient) // Filter mutations by mutationKey -await queryClient.isMutating({ mutationKey: ['post'] }) +await isMutating(queryClient, { mutationKey: ['post'] }) // Filter mutations using a predicate function -await queryClient.isMutating({ +await isMutating(queryClient, { predicate: (mutation) => mutation.state.variables?.id === 1, }) ``` diff --git a/docs/framework/react/guides/important-defaults.md b/docs/framework/react/guides/important-defaults.md index e8b091eeb95..5460fc57fad 100644 --- a/docs/framework/react/guides/important-defaults.md +++ b/docs/framework/react/guides/important-defaults.md @@ -5,7 +5,7 @@ title: Important Defaults Out of the box, TanStack Query is configured with **aggressive but sane** defaults. **Sometimes these defaults can catch new users off guard or make learning/debugging difficult if they are unknown by the user.** Keep them in mind as you continue to learn and use TanStack Query: -- Query instances via `useQuery` or `useInfiniteQuery` by default **consider cached data as stale**. +- Queries observed through `useQuery` by default **consider cached data as stale**. > To change this behavior, you can configure your queries both globally and per-query using the `staleTime` option. Specifying a longer `staleTime` means queries will not refetch their data as often @@ -14,7 +14,7 @@ Out of the box, TanStack Query is configured with **aggressive but sane** defaul - set `staleTime` to `Infinity` to never trigger a refetch until the Query is [invalidated manually](./query-invalidation.md). - set `staleTime` to `'static'` to **never** trigger a refetch, even if the Query is [invalidated manually](./query-invalidation.md). -> `'static'` and `Infinity` both prevent staleness-based refetches, but `'static'` is stricter: `queryClient.invalidateQueries()` can invalidate a query with `staleTime: Infinity`, but has no effect on `staleTime: 'static'`. `refetchOnMount`, `refetchOnWindowFocus`, and `refetchOnReconnect` set to `"always"` are also blocked by `'static'`. Use `'static'` for data that cannot change while the app is running: feature flags fetched at boot, user permissions loaded at login, static reference tables. Use `Infinity` when you still want manual invalidation to work. +> `'static'` and `Infinity` both prevent staleness-based refetches, but `'static'` is stricter: `invalidateQueries(queryClient)` can invalidate a query with `staleTime: Infinity`, but has no effect on `staleTime: 'static'`. `refetchOnMount`, `refetchOnWindowFocus`, and `refetchOnReconnect` set to `"always"` are also blocked by `'static'`. Use `'static'` for data that cannot change while the app is running: feature flags fetched at boot, user permissions loaded at login, static reference tables. Use `Infinity` when you still want manual invalidation to work. - Stale queries are refetched automatically in the background when: - New instances of the query mount @@ -25,7 +25,7 @@ Out of the box, TanStack Query is configured with **aggressive but sane** defaul - Queries can optionally be configured with a `refetchInterval` to trigger refetches periodically, which is independent of the `staleTime` setting. See [Polling](./polling.md) for details. -- Query results that have no more active instances of `useQuery`, `useInfiniteQuery` or query observers are labeled as "inactive" and remain in the cache in case they are used again at a later time. +- Query results that have no more active subscribers in `useQuery` or other query observers are labeled as "inactive" and remain in the cache in case they are used again at a later time. - By default, "inactive" queries are garbage collected after **5 minutes**. > To change this, you can alter the default `gcTime` for queries to something other than `5 * 60 * 1000` milliseconds. diff --git a/docs/framework/react/guides/infinite-queries.md b/docs/framework/react/guides/infinite-queries.md index dccadec1a1b..ce89b63d926 100644 --- a/docs/framework/react/guides/infinite-queries.md +++ b/docs/framework/react/guides/infinite-queries.md @@ -3,9 +3,9 @@ id: infinite-queries title: Infinite Queries --- -Rendering lists that can additively "load more" data onto an existing set of data or "infinite scroll" is also a very common UI pattern. TanStack Query supports a useful version of `useQuery` called `useInfiniteQuery` for querying these types of lists. +Pass `infiniteQueryOptions` to `useQuery` to load additional pages when a user scrolls or clicks “Load more”. -When using `useInfiniteQuery`, you'll notice a few things are different: +When using `infiniteQueryOptions`, you'll notice a few things are different: - `data` is now an object containing infinite query data: - `data.pages` array containing the fetched pages @@ -36,14 +36,19 @@ fetch('/api/projects?cursor=9') With this information, we can create a "Load More" UI by: -- Waiting for `useInfiniteQuery` to request the first group of data by default +- Waiting for `useQuery` to request the first group of data by default - Returning the information for the next query in `getNextPageParam` - Calling `fetchNextPage` function [//]: # 'Example' ```tsx -import { useInfiniteQuery } from '@tanstack/react-query' +import { + useQuery, + infiniteQueryOptions, + isFetching, + isFetchingNextPage, +} from '@tanstack/react-query' function Projects() { const fetchProjects = async ({ pageParam }) => { @@ -51,28 +56,22 @@ function Projects() { return res.json() } - const { - data, - error, - fetchNextPage, - hasNextPage, - isFetching, - isFetchingNextPage, - status, - } = useInfiniteQuery({ - queryKey: ['projects'], - queryFn: fetchProjects, - initialPageParam: 0, - getNextPageParam: (lastPage, pages) => lastPage.nextCursor, - }) + const infiniteQueryResult = useQuery( + infiniteQueryOptions({ + queryKey: ['projects'], + queryFn: fetchProjects, + initialPageParam: 0, + getNextPageParam: (lastPage, pages) => lastPage.nextCursor, + }), + ) - return status === 'pending' ? ( + return infiniteQueryResult.status === 'pending' ? (

Loading...

- ) : status === 'error' ? ( -

Error: {error.message}

+ ) : infiniteQueryResult.status === 'error' ? ( +

Error: {infiniteQueryResult.error.message}

) : ( <> - {data.pages.map((group, i) => ( + {infiniteQueryResult.data.pages.map((group, i) => ( {group.data.map((project) => (

{project.name}

@@ -81,17 +80,24 @@ function Projects() { ))}
-
{isFetching && !isFetchingNextPage ? 'Fetching...' : null}
+
+ {isFetching(infiniteQueryResult) && + !isFetchingNextPage(infiniteQueryResult) + ? 'Fetching...' + : null} +
) } @@ -126,13 +132,15 @@ Bi-directional lists can be implemented by using the `getPreviousPageParam`, `fe [//]: # 'Example3' ```tsx -useInfiniteQuery({ - queryKey: ['projects'], - queryFn: fetchProjects, - initialPageParam: 0, - getNextPageParam: (lastPage, pages) => lastPage.nextCursor, - getPreviousPageParam: (firstPage, pages) => firstPage.prevCursor, -}) +useQuery( + infiniteQueryOptions({ + queryKey: ['projects'], + queryFn: fetchProjects, + initialPageParam: 0, + getNextPageParam: (lastPage, pages) => lastPage.nextCursor, + getPreviousPageParam: (firstPage, pages) => firstPage.prevCursor, + }), +) ``` [//]: # 'Example3' @@ -144,14 +152,16 @@ Sometimes you may want to show the pages in reversed order. If this is case, you [//]: # 'Example4' ```tsx -useInfiniteQuery({ - queryKey: ['projects'], - queryFn: fetchProjects, - select: (data) => ({ - pages: [...data.pages].reverse(), - pageParams: [...data.pageParams].reverse(), +useQuery( + infiniteQueryOptions({ + queryKey: ['projects'], + queryFn: fetchProjects, + select: select((data) => ({ + pages: [...data.pages].reverse(), + pageParams: [...data.pageParams].reverse(), + })), }), -}) +) ``` [//]: # 'Example4' @@ -163,7 +173,7 @@ useInfiniteQuery({ [//]: # 'Example5' ```tsx -queryClient.setQueryData(['projects'], (data) => ({ +setQueryData(queryClient, ['projects'], (data) => ({ pages: data.pages.slice(1), pageParams: data.pageParams.slice(1), })) @@ -181,7 +191,7 @@ const newPagesArray = page.filter((val) => val.id !== updatedId), ) ?? [] -queryClient.setQueryData(['projects'], (data) => ({ +setQueryData(queryClient, ['projects'], (data) => ({ pages: newPagesArray, pageParams: data.pageParams, })) @@ -194,7 +204,7 @@ queryClient.setQueryData(['projects'], (data) => ({ [//]: # 'Example7' ```tsx -queryClient.setQueryData(['projects'], (data) => ({ +setQueryData(queryClient, ['projects'], (data) => ({ pages: data.pages.slice(0, 1), pageParams: data.pageParams.slice(0, 1), })) @@ -218,14 +228,16 @@ In the following example only 3 pages are kept in the query data pages array. If [//]: # 'Example8' ```tsx -useInfiniteQuery({ - queryKey: ['projects'], - queryFn: fetchProjects, - initialPageParam: 0, - getNextPageParam: (lastPage, pages) => lastPage.nextCursor, - getPreviousPageParam: (firstPage, pages) => firstPage.prevCursor, - maxPages: 3, -}) +useQuery( + infiniteQueryOptions({ + queryKey: ['projects'], + queryFn: fetchProjects, + initialPageParam: 0, + getNextPageParam: (lastPage, pages) => lastPage.nextCursor, + getPreviousPageParam: (firstPage, pages) => firstPage.prevCursor, + maxPages: 3, + }), +) ``` [//]: # 'Example8' @@ -237,23 +249,25 @@ If your API doesn't return a cursor, you can use the `pageParam` as a cursor. Be [//]: # 'Example9' ```tsx -return useInfiniteQuery({ - queryKey: ['projects'], - queryFn: fetchProjects, - initialPageParam: 0, - getNextPageParam: (lastPage, allPages, lastPageParam) => { - if (lastPage.length === 0) { - return undefined - } - return lastPageParam + 1 - }, - getPreviousPageParam: (firstPage, allPages, firstPageParam) => { - if (firstPageParam <= 1) { - return undefined - } - return firstPageParam - 1 - }, -}) +return useQuery( + infiniteQueryOptions({ + queryKey: ['projects'], + queryFn: fetchProjects, + initialPageParam: 0, + getNextPageParam: (lastPage, allPages, lastPageParam) => { + if (lastPage.length === 0) { + return undefined + } + return lastPageParam + 1 + }, + getPreviousPageParam: (firstPage, allPages, firstPageParam) => { + if (firstPageParam <= 1) { + return undefined + } + return firstPageParam - 1 + }, + }), +) ``` [//]: # 'Example9' diff --git a/docs/framework/react/guides/initial-query-data.md b/docs/framework/react/guides/initial-query-data.md index 20ae385e62b..e6de4b93154 100644 --- a/docs/framework/react/guides/initial-query-data.md +++ b/docs/framework/react/guides/initial-query-data.md @@ -8,8 +8,8 @@ There are many ways to supply initial data for a query to the cache before you n - Declaratively: - Provide `initialData` to a query to prepopulate its cache if empty - Imperatively: - - [Prefetch the data using `queryClient.query`](./prefetching.md) - - [Manually place the data into the cache using `queryClient.setQueryData`](./prefetching.md) + - [Prefetch the data using `query`](./prefetching.md) + - [Manually place the data into the cache using `setQueryData`](./prefetching.md) ## Using `initialData` to prepopulate a query @@ -20,11 +20,13 @@ There may be times when you already have the initial data for a query available [//]: # 'Example' ```tsx -const result = useQuery({ - queryKey: ['todos'], - queryFn: () => fetch('/todos'), - initialData: initialTodos, -}) +const result = useQuery( + queryOptions({ + queryKey: ['todos'], + queryFn: () => fetch('/todos'), + initialData: initialTodos, + }), +) ``` [//]: # 'Example' @@ -39,11 +41,13 @@ By default, `initialData` is treated as totally fresh, as if it were just fetche ```tsx // Will show initialTodos immediately, but also immediately refetch todos after mount - const result = useQuery({ - queryKey: ['todos'], - queryFn: () => fetch('/todos'), - initialData: initialTodos, - }) + const result = useQuery( + queryOptions({ + queryKey: ['todos'], + queryFn: () => fetch('/todos'), + initialData: initialTodos, + }), + ) ``` [//]: # 'Example2' @@ -54,12 +58,14 @@ By default, `initialData` is treated as totally fresh, as if it were just fetche ```tsx // Show initialTodos immediately, but won't refetch until another interaction event is encountered after 1000 ms - const result = useQuery({ - queryKey: ['todos'], - queryFn: () => fetch('/todos'), - initialData: initialTodos, - staleTime: 1000, - }) + const result = useQuery( + queryOptions({ + queryKey: ['todos'], + queryFn: () => fetch('/todos'), + initialData: initialTodos, + staleTime: 1000, + }), + ) ``` [//]: # 'Example3' @@ -70,14 +76,16 @@ By default, `initialData` is treated as totally fresh, as if it were just fetche ```tsx // Show initialTodos immediately, but won't refetch until another interaction event is encountered after 1000 ms - const result = useQuery({ - queryKey: ['todos'], - queryFn: () => fetch('/todos'), - initialData: initialTodos, - staleTime: 60 * 1000, // 1 minute - // This could be 10 seconds ago or 10 minutes ago - initialDataUpdatedAt: initialTodosUpdatedTimestamp, // eg. 1608412420052 - }) + const result = useQuery( + queryOptions({ + queryKey: ['todos'], + queryFn: () => fetch('/todos'), + initialData: initialTodos, + staleTime: 60 * 1000, // 1 minute + // This could be 10 seconds ago or 10 minutes ago + initialDataUpdatedAt: initialTodosUpdatedTimestamp, // eg. 1608412420052 + }), + ) ``` [//]: # 'Example4' @@ -93,11 +101,13 @@ If the process for accessing a query's initial data is intensive or just not som [//]: # 'Example5' ```tsx -const result = useQuery({ - queryKey: ['todos'], - queryFn: () => fetch('/todos'), - initialData: () => getExpensiveTodos(), -}) +const result = useQuery( + queryOptions({ + queryKey: ['todos'], + queryFn: () => fetch('/todos'), + initialData: () => getExpensiveTodos(), + }), +) ``` [//]: # 'Example5' @@ -109,14 +119,16 @@ In some circumstances, you may be able to provide the initial data for a query f [//]: # 'Example6' ```tsx -const result = useQuery({ - queryKey: ['todo', todoId], - queryFn: () => fetch('/todos'), - initialData: () => { - // Use a todo from the 'todos' query as the initial data for this todo query - return queryClient.getQueryData(['todos'])?.find((d) => d.id === todoId) - }, -}) +const result = useQuery( + queryOptions({ + queryKey: ['todo', todoId], + queryFn: () => fetch('/todos'), + initialData: () => { + // Use a todo from the 'todos' query as the initial data for this todo query + return getQueryData(queryClient, ['todos'])?.find((d) => d.id === todoId) + }, + }), +) ``` [//]: # 'Example6' @@ -128,41 +140,45 @@ Getting initial data from the cache means the source query you're using to look [//]: # 'Example7' ```tsx -const result = useQuery({ - queryKey: ['todos', todoId], - queryFn: () => fetch(`/todos/${todoId}`), - initialData: () => - queryClient.getQueryData(['todos'])?.find((d) => d.id === todoId), - initialDataUpdatedAt: () => - queryClient.getQueryState(['todos'])?.dataUpdatedAt, -}) +const result = useQuery( + queryOptions({ + queryKey: ['todos', todoId], + queryFn: () => fetch(`/todos/${todoId}`), + initialData: () => + getQueryData(queryClient, ['todos'])?.find((d) => d.id === todoId), + initialDataUpdatedAt: () => + getQueryState(queryClient, ['todos'])?.dataUpdatedAt, + }), +) ``` [//]: # 'Example7' ### Conditional Initial Data from Cache -If the source query you're using to look up the initial data from is old, you may not want to use the cached data at all and just fetch from the server. To make this decision easier, you can use the `queryClient.getQueryState` method instead to get more information about the source query, including a `state.dataUpdatedAt` timestamp you can use to decide if the query is "fresh" enough for your needs: +If the source query you're using to look up the initial data from is old, you may not want to use the cached data at all and just fetch from the server. To make this decision easier, you can use the `getQueryState` method instead to get more information about the source query, including a `state.dataUpdatedAt` timestamp you can use to decide if the query is "fresh" enough for your needs: [//]: # 'Example8' ```tsx -const result = useQuery({ - queryKey: ['todo', todoId], - queryFn: () => fetch(`/todos/${todoId}`), - initialData: () => { - // Get the query state - const state = queryClient.getQueryState(['todos']) - - // If the query exists and has data that is no older than 10 seconds... - if (state && Date.now() - state.dataUpdatedAt <= 10 * 1000) { - // return the individual todo - return state.data.find((d) => d.id === todoId) - } - - // Otherwise, return undefined and let it fetch from a hard loading state! - }, -}) +const result = useQuery( + queryOptions({ + queryKey: ['todo', todoId], + queryFn: () => fetch(`/todos/${todoId}`), + initialData: () => { + // Get the query state + const state = getQueryState(queryClient, ['todos']) + + // If the query exists and has data that is no older than 10 seconds... + if (state && Date.now() - state.dataUpdatedAt <= 10 * 1000) { + // return the individual todo + return state.data.find((d) => d.id === todoId) + } + + // Otherwise, return undefined and let it fetch from a hard loading state! + }, + }), +) ``` [//]: # 'Example8' diff --git a/docs/framework/react/guides/invalidations-from-mutations.md b/docs/framework/react/guides/invalidations-from-mutations.md index c3ccc1032be..ab0ca923e65 100644 --- a/docs/framework/react/guides/invalidations-from-mutations.md +++ b/docs/framework/react/guides/invalidations-from-mutations.md @@ -20,7 +20,11 @@ When a successful `postTodo` mutation happens, we likely want all `todos` querie [//]: # 'Example2' ```tsx -import { useMutation, useQueryClient } from '@tanstack/react-query' +import { + useMutation, + useQueryClient, + invalidateQueries, +} from '@tanstack/react-query' const queryClient = useQueryClient() @@ -29,12 +33,12 @@ const mutation = useMutation({ mutationFn: addTodo, onSuccess: async () => { // If you're invalidating a single query - await queryClient.invalidateQueries({ queryKey: ['todos'] }) + await invalidateQueries(queryClient, { queryKey: ['todos'] }) // If you're invalidating multiple queries await Promise.all([ - queryClient.invalidateQueries({ queryKey: ['todos'] }), - queryClient.invalidateQueries({ queryKey: ['reminders'] }), + invalidateQueries(queryClient, { queryKey: ['todos'] }), + invalidateQueries(queryClient, { queryKey: ['reminders'] }), ]) }, }) diff --git a/docs/framework/react/guides/migrating-to-v6.md b/docs/framework/react/guides/migrating-to-v6.md new file mode 100644 index 00000000000..973662eeeb6 --- /dev/null +++ b/docs/framework/react/guides/migrating-to-v6.md @@ -0,0 +1,118 @@ +--- +id: migrating-to-v6 +title: Migrating to v6 +--- + +## Client operations across frameworks + +A `QueryClient` still owns the query cache, defaults, and subscriptions for one application. Import the operations your application needs from its framework adapter. Each operation takes the client first. Vue's exports also unwrap reactive keys and filters. + +```ts +import { + QueryClient, + getQueryData, + invalidateQueries, + query, +} from '@tanstack/query-core' + +const client = new QueryClient() +const posts = { queryKey: ['posts'], queryFn: fetchPosts } + +await query(client, posts) +const cached = getQueryData(client, posts.queryKey) +await invalidateQueries(client, { queryKey: posts.queryKey }) +``` + +| Earlier call | v6 | +| ---------------------------------- | --------------------------------------- | +| `client.query(options)` | `query(client, options)` | +| `client.infiniteQuery(options)` | `infiniteQuery(client, options)` | +| `client.setQueryData(key, update)` | `setQueryData(client, key, update)` | +| `client.isFetching(filters)` | `countFetchingQueries(client, filters)` | +| `client.getMutationCache()` | `getMutationCache(client)` | +| `cache.find(filters)` | `findCachedQuery(cache, filters)` | +| `entry.isActive()` | `isQueryActive(entry)` | + +For framework-independent code, import these functions from `@tanstack/query-core`. A read-only client can operate for its entire lifetime without constructing a mutation cache. The first mutation or explicit call to `getMutationCache(client)` obtains the cache shared by later callers. + +## Single queries in React and Preact + +Choose the factory when defining the query. All four factories produce options that `useQuery` can read. TypeScript rejects a plain object passed directly to the hook. + +| Subscriber | Factory | Result | +| ------------------------ | ------------------------------ | ------------------------------------------------------------------------------- | +| Ordinary query | `queryOptions` | Check the status to narrow data or error. | +| Suspense query | `suspenseQueryOptions` | A running query returns defined data after the boundary resolves. | +| Paginated query | `infiniteQueryOptions` | Receives the page data and pagination controls. | +| Paginated Suspense query | `suspenseInfiniteQueryOptions` | Receives defined page data and pagination controls after the boundary resolves. | + +```tsx +import { + isLoadingError, + isSuccess, + queryOptions, + useQuery, +} from '@tanstack/react-query' + +const postQueryOptions = (id: number) => + queryOptions({ queryKey: ['post', id], queryFn: () => fetchPost(id) }) + +function Article({ id }: { id: number }) { + const article = useQuery(postQueryOptions(id)) + if (isSuccess(article)) return

{article.data.title}

+ if (isLoadingError(article)) return

{article.error.message}

+ return +} +``` + +The checks narrow the original result, including the selected data type and the query's error type. An error during a background refresh can coexist with previously fetched data. Use `isRefetchError(result)` to distinguish that state. + +```tsx +import { suspenseQueryOptions, useQuery } from '@tanstack/react-query' +import { Suspense } from 'react' + +const postSuspenseOptions = (id: number) => + suspenseQueryOptions({ queryKey: ['post', id], queryFn: () => fetchPost(id) }) + +function ArticleTitle({ id }: { id: number }) { + const { data } = useQuery(postSuspenseOptions(id)) + return

{data.title}

+} + +function Article({ id }: { id: number }) { + return ( + }> + + + ) +} +``` + +When the fetch function can be `skipToken`, a skipped Suspense reader can return cached data or `undefined`. For a list whose length changes, keep using `useQueries` or `useSuspenseQueries` so the component keeps a stable hook order. + +## Optional query behavior + +Import the helper where the feature is used, including when setting a client-wide default. + +```ts +import { + keepPreviousData, + placeholderData, + queryOptions, + refetchInterval, + select, +} from '@tanstack/react-query' + +const catalogOptions = (page: number) => + queryOptions({ + queryKey: ['catalog', page], + queryFn: () => fetchProducts(page), + refetchInterval: refetchInterval(3000), + placeholderData: placeholderData(keepPreviousData), + select: select((products) => products.map((product) => product.title)), + }) +``` + +For ordinary React or Preact queries, pass `throwOnError: [throwOnError, true]` to opt into error boundaries. The second element can also be a predicate receiving the error and the cached query. Suspense factories handle initial fallback and errors through the boundary. Structural sharing remains enabled by default. + +In an application that lazy loads a bookmarks panel, keep its mutation and pagination imports in the lazy module. An initial catalog read can then ship just the query reader. A bundler can still place functionality used by both routes into shared chunks. diff --git a/docs/framework/react/guides/mutations.md b/docs/framework/react/guides/mutations.md index def2dba1032..9215fd51afa 100644 --- a/docs/framework/react/guides/mutations.md +++ b/docs/framework/react/guides/mutations.md @@ -59,7 +59,7 @@ Beyond those primary states, more information is available depending on the stat In the example above, you also saw that you can pass variables to your mutations function by calling the `mutate` function with a **single variable or object**. -Even with just variables, mutations aren't all that special, but when used with the `onSuccess` option, the [Query Client's `invalidateQueries` method](../reference/classes/QueryClient.md#invalidatequeries) and the [Query Client's `setQueryData` method](../reference/classes/QueryClient.md#setquerydata), mutations become a very powerful tool. +Even with just variables, mutations aren't all that special, but when used with the `onSuccess` option, the [`invalidateQueries` operation](./query-invalidation.md) and the [`setQueryData` operation](./migrating-to-v6.md#client-operations-across-frameworks), mutations become a very powerful tool. [//]: # 'Info1' @@ -294,24 +294,24 @@ Mutations can be persisted to storage if needed and resumed at a later point. Th const queryClient = new QueryClient() // Define the "addTodo" mutation -queryClient.setMutationDefaults(['addTodo'], { +setMutationDefaults(queryClient, ['addTodo'], { mutationFn: addTodo, onMutate: async (variables, context) => { // Cancel current queries for the todos list - await context.client.cancelQueries({ queryKey: ['todos'] }) + await cancelQueries(context.client, { queryKey: ['todos'] }) // Create optimistic todo const optimisticTodo = { id: uuid(), title: variables.title } // Add optimistic todo to todos list - context.client.setQueryData(['todos'], (old) => [...old, optimisticTodo]) + setQueryData(context.client, ['todos'], (old) => [...old, optimisticTodo]) // Return a result with the optimistic todo return { optimisticTodo } }, onSuccess: (result, variables, onMutateResult, context) => { // Replace optimistic todo in the todos list with the result - context.client.setQueryData(['todos'], (old) => + setQueryData(context.client, ['todos'], (old) => old.map((todo) => todo.id === onMutateResult.optimisticTodo.id ? result : todo, ), @@ -319,7 +319,7 @@ queryClient.setMutationDefaults(['addTodo'], { }, onError: (error, variables, onMutateResult, context) => { // Remove optimistic todo from the todos list - context.client.setQueryData(['todos'], (old) => + setQueryData(context.client, ['todos'], (old) => old.filter((todo) => todo.id !== onMutateResult.optimisticTodo.id), ) }, @@ -338,7 +338,7 @@ const state = dehydrate(queryClient) hydrate(queryClient, state) // Resume the paused mutations: -queryClient.resumePausedMutations() +resumePausedMutations(queryClient) ``` [//]: # 'Example10' @@ -367,7 +367,7 @@ const queryClient = new QueryClient({ }) // we need a default mutation function so that paused mutations can resume after a page reload -queryClient.setMutationDefaults(['todos'], { +setMutationDefaults(queryClient, ['todos'], { mutationFn: ({ id, data }) => { return api.updateTodo(id, data) }, @@ -380,7 +380,7 @@ export default function App() { persistOptions={{ persister }} onSuccess={() => { // resume mutations after initial restore from localStorage was successful - queryClient.resumePausedMutations() + resumePausedMutations(queryClient) }} > @@ -398,16 +398,14 @@ We also have an extensive [offline example](../examples/offline-tanstack-router) ## Mutation Scopes -Per default, all mutations run in parallel - even if you invoke `.mutate()` of the same mutation multiple times. Mutations can be given a `scope` with an `id` to avoid that. All mutations with the same `scope.id` will run in serial, which means when they are triggered, they will start in `isPaused: true` state if there is already a mutation for that scope in progress. They will be put into a queue and will automatically resume once their time in the queue has come. +Per default, all mutations run in parallel - even if you invoke `.mutate()` of the same mutation multiple times. Use `scope: serialScope(id)` to queue related mutations. All mutations with the same scope ID will run in serial, which means when they are triggered, they will start in `isPaused: true` state if there is already a mutation for that scope in progress. They will be put into a queue and will automatically resume once their time in the queue has come. [//]: # 'ExampleScopes' ```tsx const mutation = useMutation({ mutationFn: addTodo, - scope: { - id: 'todo', - }, + scope: serialScope('todo'), }) ``` diff --git a/docs/framework/react/guides/network-mode.md b/docs/framework/react/guides/network-mode.md index 0e9a7183eb3..38b270f9201 100644 --- a/docs/framework/react/guides/network-mode.md +++ b/docs/framework/react/guides/network-mode.md @@ -15,7 +15,7 @@ In this mode, Queries and Mutations will not fire unless you have network connec - `paused`: The query is not executing - it is `paused` until you have connection again - `idle`: The query is not fetching and not paused -The flags `isFetching` and `isPaused` are derived from this state and exposed for convenience. +The helpers `isFetching(result)` and `isPaused(result)` read this state from a query result. > Keep in mind that it might not be enough to check for `pending` state to show a loading spinner. Queries can be in `state: 'pending'`, but `fetchStatus: 'paused'` if they are mounting for the first time, and you have no network connection. diff --git a/docs/framework/react/guides/optimistic-updates.md b/docs/framework/react/guides/optimistic-updates.md index c35fdb37009..7bc103f600a 100644 --- a/docs/framework/react/guides/optimistic-updates.md +++ b/docs/framework/react/guides/optimistic-updates.md @@ -16,7 +16,7 @@ const addTodoMutation = useMutation({ mutationFn: (newTodo: string) => axios.post('/api/data', { text: newTodo }), // make sure to _return_ the Promise from the query invalidation // so that the mutation stays in `pending` state until the refetch is finished - onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), + onSettled: () => invalidateQueries(queryClient, { queryKey: ['todos'] }), }) const { isPending, submittedAt, variables, mutate, isError } = addTodoMutation @@ -68,7 +68,7 @@ This approach works very well if the mutation and the query live in the same com // somewhere in your app const { mutate } = useMutation({ mutationFn: (newTodo: string) => axios.post('/api/data', { text: newTodo }), - onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), + onSettled: () => invalidateQueries(queryClient, { queryKey: ['todos'] }), mutationKey: ['addTodo'], }) @@ -102,13 +102,13 @@ useMutation({ onMutate: async (newTodo, context) => { // Cancel any outgoing refetches // (so they don't overwrite our optimistic update) - await context.client.cancelQueries({ queryKey: ['todos'] }) + await cancelQueries(context.client, { queryKey: ['todos'] }) // Snapshot the previous value - const previousTodos = context.client.getQueryData(['todos']) + const previousTodos = getQueryData(context.client, ['todos']) // Optimistically update to the new value - context.client.setQueryData(['todos'], (old) => [...old, newTodo]) + setQueryData(context.client, ['todos'], (old) => [...old, newTodo]) // Return a result with the snapshotted value return { previousTodos } @@ -116,11 +116,11 @@ useMutation({ // If the mutation fails, // use the result returned from onMutate to roll back onError: (err, newTodo, onMutateResult, context) => { - context.client.setQueryData(['todos'], onMutateResult.previousTodos) + setQueryData(context.client, ['todos'], onMutateResult.previousTodos) }, // Always refetch after error or success: onSettled: (data, error, variables, onMutateResult, context) => - context.client.invalidateQueries({ queryKey: ['todos'] }), + invalidateQueries(context.client, { queryKey: ['todos'] }), }) ``` @@ -137,27 +137,28 @@ useMutation({ onMutate: async (newTodo, context) => { // Cancel any outgoing refetches // (so they don't overwrite our optimistic update) - await context.client.cancelQueries({ queryKey: ['todos', newTodo.id] }) + await cancelQueries(context.client, { queryKey: ['todos', newTodo.id] }) // Snapshot the previous value - const previousTodo = context.client.getQueryData(['todos', newTodo.id]) + const previousTodo = getQueryData(context.client, ['todos', newTodo.id]) // Optimistically update to the new value - context.client.setQueryData(['todos', newTodo.id], newTodo) + setQueryData(context.client, ['todos', newTodo.id], newTodo) // Return a result with the previous and new todo return { previousTodo, newTodo } }, // If the mutation fails, use the result we returned above onError: (err, newTodo, onMutateResult, context) => { - context.client.setQueryData( + setQueryData( + context.client, ['todos', onMutateResult.newTodo.id], onMutateResult.previousTodo, ) }, // Always refetch after error or success: onSettled: (newTodo, error, variables, onMutateResult, context) => - context.client.invalidateQueries({ queryKey: ['todos', newTodo.id] }), + invalidateQueries(context.client, { queryKey: ['todos', newTodo.id] }), }) ``` diff --git a/docs/framework/react/guides/paginated-queries.md b/docs/framework/react/guides/paginated-queries.md index 258d744c78a..6d62028c978 100644 --- a/docs/framework/react/guides/paginated-queries.md +++ b/docs/framework/react/guides/paginated-queries.md @@ -8,10 +8,12 @@ Rendering paginated data is a very common UI pattern and in TanStack Query, it " [//]: # 'Example' ```tsx -const result = useQuery({ - queryKey: ['projects', page], - queryFn: () => fetchProjects(page), -}) +const result = useQuery( + queryOptions({ + queryKey: ['projects', page], + queryFn: () => fetchProjects(page), + }), +) ``` [//]: # 'Example' @@ -24,7 +26,7 @@ This experience is not optimal and unfortunately is how many tools today insist ## Better Paginated Queries with `placeholderData` -Consider the following example where we would ideally want to increment a pageIndex (or cursor) for a query. If we were to use `useQuery`, **it would still technically work fine**, but the UI would jump in and out of the `success` and `pending` states as different queries are created and destroyed for each page or cursor. By setting `placeholderData` to `(previousData) => previousData` or `keepPreviousData` function exported from TanStack Query, we get a few new things: +Consider the following example where we would ideally want to increment a pageIndex (or cursor) for a query. If we were to use `useQuery`, **it would still technically work fine**, but the UI would jump in and out of the `success` and `pending` states as different queries are created and destroyed for each page or cursor. By setting `placeholderData: placeholderData(keepPreviousData)`, we get a few new things: - **The data from the last successful fetch is available while new data is being requested, even though the query key has changed**. - When the new data arrives, the previous `data` is seamlessly swapped to show the new data. @@ -33,7 +35,15 @@ Consider the following example where we would ideally want to increment a pageIn [//]: # 'Example2' ```tsx -import { keepPreviousData, useQuery } from '@tanstack/react-query' +import { + keepPreviousData, + useQuery, + queryOptions, + isPending, + isError, + isFetching, + placeholderData, +} from '@tanstack/react-query' import React from 'react' function Todos() { @@ -42,22 +52,23 @@ function Todos() { const fetchProjects = (page = 0) => fetch('/api/projects?page=' + page).then((res) => res.json()) - const { isPending, isError, error, data, isFetching, isPlaceholderData } = - useQuery({ + const queryResult = useQuery( + queryOptions({ queryKey: ['projects', page], queryFn: () => fetchProjects(page), - placeholderData: keepPreviousData, - }) + placeholderData: placeholderData(keepPreviousData), + }), + ) return (
- {isPending ? ( + {isPending(queryResult) ? (
Loading...
- ) : isError ? ( -
Error: {error.message}
+ ) : isError(queryResult) ? ( +
Error: {queryResult.error.message}
) : (
- {data.projects.map((project) => ( + {queryResult.data.projects.map((project) => (

{project.name}

))}
@@ -71,16 +82,16 @@ function Todos() { - {isFetching ? Loading... : null} + {isFetching(queryResult) ? Loading... : null}
) } @@ -90,4 +101,4 @@ function Todos() { ## Lagging Infinite Query results with `placeholderData` -While not as common, the `placeholderData` option also works flawlessly with the `useInfiniteQuery` hook, so you can seamlessly allow your users to continue to see cached data while infinite query keys change over time. +While not as common, the `placeholderData` option also works flawlessly with `useQuery(infiniteQueryOptions(...))`, so you can seamlessly allow your users to continue to see cached data while infinite query keys change over time. diff --git a/docs/framework/react/guides/parallel-queries.md b/docs/framework/react/guides/parallel-queries.md index b842aac40cd..22fe1f29b70 100644 --- a/docs/framework/react/guides/parallel-queries.md +++ b/docs/framework/react/guides/parallel-queries.md @@ -7,16 +7,16 @@ title: Parallel Queries ## Manual Parallel Queries -When the number of parallel queries does not change, there is **no extra effort** to use parallel queries. Just use any number of TanStack Query's `useQuery` and `useInfiniteQuery` hooks side-by-side! +When the number of parallel queries does not change, there is **no extra effort** to use parallel queries. Call `useQuery` once for each regular or infinite descriptor. [//]: # 'Example' ```tsx function App () { // The following queries will execute in parallel - const usersQuery = useQuery({ queryKey: ['users'], queryFn: fetchUsers }) - const teamsQuery = useQuery({ queryKey: ['teams'], queryFn: fetchTeams }) - const projectsQuery = useQuery({ queryKey: ['projects'], queryFn: fetchProjects }) + const usersQuery = useQuery(queryOptions({ queryKey: ['users'], queryFn: fetchUsers })) + const teamsQuery = useQuery(queryOptions({ queryKey: ['teams'], queryFn: fetchTeams })) + const projectsQuery = useQuery(queryOptions({ queryKey: ['projects'], queryFn: fetchProjects })) ... } ``` @@ -24,7 +24,7 @@ function App () { [//]: # 'Example' [//]: # 'Info' -> When using React Query in suspense mode, this pattern of parallelism does not work, since the first query would throw a promise internally and would suspend the component before the other queries run. To get around this, you'll either need to use the `useSuspenseQueries` hook (which is suggested) or orchestrate your own parallelism with separate components for each `useSuspenseQuery` instance. +> When using React Query in suspense mode, this pattern of parallelism does not work, since the first query would throw a promise internally and would suspend the component before the other queries run. To get around this, you'll either need to use the `useSuspenseQueries` hook (which is suggested) or orchestrate your own parallelism with separate components for each Suspense query. [//]: # 'Info' diff --git a/docs/framework/react/guides/placeholder-query-data.md b/docs/framework/react/guides/placeholder-query-data.md index c8e5c8ccef7..dd1959becbf 100644 --- a/docs/framework/react/guides/placeholder-query-data.md +++ b/docs/framework/react/guides/placeholder-query-data.md @@ -12,9 +12,9 @@ Placeholder data allows a query to behave as if it already has data, similar to There are a few ways to supply placeholder data for a query to the cache before you need it: - Declaratively: - - Provide `placeholderData` to a query to prepopulate its cache if empty + - Wrap a value or factory in `placeholderData(...)` to display it until the first cached result arrives - Imperatively: - - [Prefetch or fetch the data using `queryClient` and the `placeholderData` option](./prefetching.md) + - [Prefetch data with `query(queryClient, options)` to populate the cache](./prefetching.md) When we use `placeholderData`, our Query will not be in a `pending` state - it will start out as being in `success` state, because we have `data` to display - even if that data is just "placeholder" data. To distinguish it from "real" data, we will also have the `isPlaceholderData` flag set to `true` on the Query result. @@ -24,11 +24,13 @@ When we use `placeholderData`, our Query will not be in a `pending` state - it w ```tsx function Todos() { - const result = useQuery({ - queryKey: ['todos'], - queryFn: () => fetch('/todos'), - placeholderData: placeholderTodos, - }) + const result = useQuery( + queryOptions({ + queryKey: ['todos'], + queryFn: () => fetch('/todos'), + placeholderData: placeholderData(placeholderTodos), + }), + ) } ``` @@ -41,12 +43,14 @@ If the process for accessing a query's placeholder data is intensive or just not ```tsx function Todos() { - const placeholderData = useMemo(() => generateFakeTodos(), []) - const result = useQuery({ - queryKey: ['todos'], - queryFn: () => fetch('/todos'), - placeholderData, - }) + const placeholderTodos = useMemo(() => generateFakeTodos(), []) + const result = useQuery( + queryOptions({ + queryKey: ['todos'], + queryFn: () => fetch('/todos'), + placeholderData: placeholderData(placeholderTodos), + }), + ) } ``` @@ -59,11 +63,15 @@ function Todos() { [//]: # 'ExampleFunction' ```tsx -const result = useQuery({ - queryKey: ['todos', id], - queryFn: () => fetch(`/todos/${id}`), - placeholderData: (previousData, previousQuery) => previousData, -}) +const result = useQuery( + queryOptions({ + queryKey: ['todos', id], + queryFn: () => fetch(`/todos/${id}`), + placeholderData: placeholderData( + (previousData, previousQuery) => previousData, + ), + }), +) ``` [//]: # 'ExampleFunction' @@ -77,17 +85,19 @@ In some circumstances, you may be able to provide the placeholder data for a que ```tsx function BlogPost({ blogPostId }) { const queryClient = useQueryClient() - const result = useQuery({ - queryKey: ['blogPost', blogPostId], - queryFn: () => fetch(`/blogPosts/${blogPostId}`), - placeholderData: () => { - // Use the smaller/preview version of the blogPost from the 'blogPosts' - // query as the placeholder data for this blogPost query - return queryClient - .getQueryData(['blogPosts']) - ?.find((d) => d.id === blogPostId) - }, - }) + const result = useQuery( + queryOptions({ + queryKey: ['blogPost', blogPostId], + queryFn: () => fetch(`/blogPosts/${blogPostId}`), + placeholderData: placeholderData(() => { + // Use the smaller/preview version of the blogPost from the 'blogPosts' + // query as the placeholder data for this blogPost query + return getQueryData(queryClient, ['blogPosts'])?.find( + (d) => d.id === blogPostId, + ) + }), + }), + ) } ``` diff --git a/docs/framework/react/guides/polling.md b/docs/framework/react/guides/polling.md index 94e8b6472c6..f81aada41d6 100644 --- a/docs/framework/react/guides/polling.md +++ b/docs/framework/react/guides/polling.md @@ -3,16 +3,20 @@ id: polling title: Polling --- -`refetchInterval` makes a query refetch on a timer. Set it to a number in milliseconds and the query runs every N ms while there's at least one active observer: +`refetchInterval` makes a query refetch on a timer. Import the `refetchInterval` helper and pass the delay in milliseconds and the query runs every N ms while there's at least one active observer: [//]: # 'Example1' ```tsx -useQuery({ - queryKey: ['prices'], - queryFn: fetchPrices, - refetchInterval: 5 * 1000, // every 5 seconds -}) +import { queryOptions, refetchInterval, useQuery } from '@tanstack/react-query' + +useQuery( + queryOptions({ + queryKey: ['prices'], + queryFn: fetchPrices, + refetchInterval: refetchInterval(5 * 1000), // every 5 seconds + }), +) ``` [//]: # 'Example1' @@ -26,15 +30,19 @@ Pass a function instead of a number to compute the interval from the current que [//]: # 'Example2' ```tsx -useQuery({ - queryKey: ['job', jobId], - queryFn: () => fetchJobStatus(jobId), - refetchInterval: (query) => { - // Stop polling once the job finishes - if (query.state.data?.status === 'complete') return false - return 2 * 1000 - }, -}) +import { queryOptions, refetchInterval, useQuery } from '@tanstack/react-query' + +useQuery( + queryOptions({ + queryKey: ['job', jobId], + queryFn: () => fetchJobStatus(jobId), + refetchInterval: refetchInterval((query) => { + // Stop polling once the job finishes + if (query.state.data?.status === 'complete') return false + return 2 * 1000 + }), + }), +) ``` [//]: # 'Example2' @@ -48,12 +56,16 @@ By default, polling pauses when the browser tab loses focus. For dashboards or a [//]: # 'Example3' ```tsx -useQuery({ - queryKey: ['portfolio'], - queryFn: fetchPortfolio, - refetchInterval: 30 * 1000, - refetchIntervalInBackground: true, -}) +import { queryOptions, refetchInterval, useQuery } from '@tanstack/react-query' + +useQuery( + queryOptions({ + queryKey: ['portfolio'], + queryFn: fetchPortfolio, + refetchInterval: refetchInterval(30 * 1000), + refetchIntervalInBackground: true, + }), +) ``` [//]: # 'Example3' @@ -65,14 +77,18 @@ Pass a function to `refetchInterval` and close over component state to control w [//]: # 'Example4' ```tsx -useQuery({ - queryKey: ['prices', tokenAddress], - queryFn: () => fetchPrice(tokenAddress), - refetchInterval: () => { - if (!tokenAddress || isPaused) return false - return 15 * 1000 - }, -}) +import { queryOptions, refetchInterval, useQuery } from '@tanstack/react-query' + +useQuery( + queryOptions({ + queryKey: ['prices', tokenAddress], + queryFn: () => fetchPrice(tokenAddress), + refetchInterval: refetchInterval(() => { + if (!tokenAddress || isPaused) return false + return 15 * 1000 + }), + }), +) ``` [//]: # 'Example4' @@ -84,12 +100,16 @@ TanStack Query detects connectivity by listening to the browser's `online` and ` [//]: # 'Example5' ```tsx -useQuery({ - queryKey: ['chainStatus'], - queryFn: fetchChainStatus, - refetchInterval: 10 * 1000, - networkMode: 'always', -}) +import { queryOptions, refetchInterval, useQuery } from '@tanstack/react-query' + +useQuery( + queryOptions({ + queryKey: ['chainStatus'], + queryFn: fetchChainStatus, + refetchInterval: refetchInterval(10 * 1000), + networkMode: 'always', + }), +) ``` [//]: # 'Example5' @@ -98,7 +118,7 @@ For more on network modes, see [Network Mode](./network-mode.md). ## Note on deduplication -Each `QueryObserver` (each component using `useQuery` with `refetchInterval`) runs its own timer. Two components subscribed to the same key with `refetchInterval: 5 * 1000` each fire their timer every 5 seconds. What gets deduplicated is concurrent in-flight fetches: if two timers fire at the same time, only one network request goes out. The timers are observer-level; the deduplication is query-level. +Each `QueryObserver` (each component using `useQuery` with `refetchInterval`) runs its own timer. Two components subscribed to the same key with `refetchInterval: refetchInterval(5 * 1000)` each fire their timer every 5 seconds. What gets deduplicated is concurrent in-flight fetches: if two timers fire at the same time, only one network request goes out. The timers are observer-level; the deduplication is query-level. [//]: # 'ReRenders' diff --git a/docs/framework/react/guides/prefetching.md b/docs/framework/react/guides/prefetching.md index c286223d51d..44611a49779 100644 --- a/docs/framework/react/guides/prefetching.md +++ b/docs/framework/react/guides/prefetching.md @@ -45,16 +45,14 @@ This is how you use `query` to prefetch: [//]: # 'ExamplePrefetchQuery' ```tsx -import { noop } from '@tanstack/react-query' +import { noop, query } from '@tanstack/react-query' const prefetchTodos = async () => { - await queryClient - .query({ - queryKey: ['todos'], - queryFn: fetchTodos, - // Swallow errors here, because usually they will fetch again in `useQuery` - }) - .catch(noop) + await query(queryClient, { + queryKey: ['todos'], + queryFn: fetchTodos, + // Swallow errors here, because usually they will fetch again in `useQuery` + }).catch(noop) } ``` @@ -65,18 +63,16 @@ Pass `getNextPageParam` when you prefetch an infinite query. On an empty cache, [//]: # 'ExamplePrefetchInfiniteQuery' ```tsx -import { noop } from '@tanstack/react-query' +import { noop, infiniteQuery } from '@tanstack/react-query' const prefetchProjects = async () => { - await queryClient - .infiniteQuery({ - queryKey: ['projects'], - queryFn: fetchProjects, - initialPageParam: 0, - getNextPageParam: (lastPage, pages) => lastPage.nextCursor, - pages: 3, // prefetch the first 3 pages - }) - .catch(noop) + await infiniteQuery(queryClient, { + queryKey: ['projects'], + queryFn: fetchProjects, + initialPageParam: 0, + getNextPageParam: (lastPage, pages) => lastPage.nextCursor, + pages: 3, // prefetch the first 3 pages + }).catch(noop) } ``` @@ -86,7 +82,7 @@ Next, let's look at how you can use these and other ways to prefetch in differen ## Prefetch in event handlers -A straightforward form of prefetching is doing it when the user interacts with something. In this example we'll use `queryClient.query` to start a prefetch on `onMouseEnter` or `onFocus`. +A straightforward form of prefetching is doing it when the user interacts with something. In this example we'll use `query` to start a prefetch on `onMouseEnter` or `onFocus`. [//]: # 'ExampleEventHandler' @@ -95,7 +91,7 @@ function ShowDetailsButton() { const queryClient = useQueryClient() const prefetch = () => { - void queryClient.query({ + void query(queryClient, { queryKey: ['details'], queryFn: getDetailsData, // Prefetch only fires when data is older than the staleTime, @@ -122,29 +118,29 @@ Prefetching during the component lifecycle is useful when we know some child or ```tsx function Article({ id }) { - const { data: articleData, isPending } = useQuery({ + const queryResult = useQuery(queryOptions({ queryKey: ['article', id], queryFn: getArticleById, - }) + })) - if (isPending) { + if (isPending(queryResult)) { return 'Loading article...' } return ( <> - - + + ) } function Comments({ id }) { - const { data, isPending } = useQuery({ + const queryResult2 = useQuery(queryOptions({ queryKey: ['article-comments', id], queryFn: getArticleCommentsById, - }) + })) ... } @@ -167,36 +163,36 @@ In that case, we can instead prefetch the query in the parent. The simplest way ```tsx function Article({ id }) { - const { data: articleData, isPending } = useQuery({ + const queryResult = useQuery(queryOptions({ queryKey: ['article', id], queryFn: getArticleById, - }) + })) // Prefetch - useQuery({ + useQuery(queryOptions({ queryKey: ['article-comments', id], queryFn: getArticleCommentsById, notifyOnChangeProps: 'none', - }) + })) - if (isPending) { + if (isPending(queryResult)) { return 'Loading article...' } return ( <> - - + + ) } function Comments({ id }) { - const { data, isPending } = useQuery({ + const queryResult2 = useQuery(queryOptions({ queryKey: ['article-comments', id], queryFn: getArticleCommentsById, - }) + })) ... } @@ -215,7 +211,7 @@ This starts fetching `'article-comments'` immediately and flattens the waterfall If you want to prefetch together with Suspense, you will have to do things a bit differently. You can't use `useSuspenseQueries` to prefetch, since the prefetch would block the component from rendering. You also can not use `useQuery` for the prefetch, because that wouldn't start the prefetch until after suspenseful query had resolved. For this scenario, you can use the [`usePrefetchQuery`](../reference/functions/usePrefetchQuery.md) or the [`usePrefetchInfiniteQuery`](../reference/functions/usePrefetchInfiniteQuery.md) hooks available in the library. -You can now use `useSuspenseQuery` in the component that actually needs the data. You _might_ want to wrap this later component in its own `` boundary so the "secondary" query we are prefetching does not block rendering of the "primary" data. +You can now pass `suspenseQueryOptions` to `useQuery` in the component that needs the data. You _might_ want to wrap this later component in its own `` boundary so the "secondary" query we are prefetching does not block rendering of the "primary" data. ```tsx function ArticleLayout({ id }) { @@ -232,46 +228,44 @@ function ArticleLayout({ id }) { } function Article({ id }) { - const { data: articleData, isPending } = useSuspenseQuery({ + const queryResult = useQuery(suspenseQueryOptions({ queryKey: ['article', id], queryFn: getArticleById, - }) + })) ... } ``` -Another way is to prefetch inside the query function. This makes sense if you know that every time an article is fetched it's very likely comments will also be needed. For this, we'll use `queryClient.query`: +Another way is to prefetch inside the query function. This makes sense if you know that every time an article is fetched it's very likely comments will also be needed. For this, we'll use `query`: ```tsx const queryClient = useQueryClient() -const { data: articleData, isPending } = useQuery({ - queryKey: ['article', id], - queryFn: (...args) => { - void queryClient - .query({ +const queryResult = useQuery( + queryOptions({ + queryKey: ['article', id], + queryFn: (...args) => { + void query(queryClient, { queryKey: ['article-comments', id], queryFn: getArticleCommentsById, - }) - .catch(noop) + }).catch(noop) - return getArticleById(...args) - }, -}) + return getArticleById(...args) + }, + }), +) ``` -Prefetching in an effect also works, but note that if you are using `useSuspenseQuery` in the same component, this effect won't run until _after_ the query finishes which might not be what you want. +Prefetching in an effect also works, but note that if you are using `suspenseQueryOptions` in the same component, this effect won't run until _after_ the query finishes which might not be what you want. ```tsx const queryClient = useQueryClient() useEffect(() => { - void queryClient - .query({ - queryKey: ['article-comments', id], - queryFn: getArticleCommentsById, - }) - .catch(noop) + void query(queryClient, { + queryKey: ['article-comments', id], + queryFn: getArticleCommentsById, + }).catch(noop) }, [queryClient, id]) ``` @@ -298,18 +292,18 @@ Sometimes we want to prefetch conditionally, based on the result of another fetc const GraphFeedItem = React.lazy(() => import('./GraphFeedItem')) function Feed() { - const { data, isPending } = useQuery({ + const queryResult = useQuery(queryOptions({ queryKey: ['feed'], queryFn: getFeed, - }) + })) - if (isPending) { + if (isPending(queryResult)) { return 'Loading feed...' } return ( <> - {data.map((feedItem) => { + {queryResult.data.map((feedItem) => { if (feedItem.type === 'GRAPH') { return } @@ -322,10 +316,10 @@ function Feed() { // GraphFeedItem.tsx function GraphFeedItem({ feedItem }) { - const { data, isPending } = useQuery({ + const queryResult2 = useQuery(queryOptions({ queryKey: ['graph', feedItem.id], queryFn: getGraphDataById, - }) + })) ... } @@ -348,14 +342,14 @@ If we can not restructure our API so `getFeed()` also returns the `getGraphDataB ```tsx function Feed() { const queryClient = useQueryClient() - const { data, isPending } = useQuery({ + const queryResult = useQuery(queryOptions({ queryKey: ['feed'], queryFn: async (...args) => { const feed = await getFeed(...args) for (const feedItem of feed) { if (feedItem.type === 'GRAPH') { - void queryClient.query({ + void query(queryClient, { queryKey: ['graph', feedItem.id], queryFn: getGraphDataById, }).catch(noop) @@ -364,7 +358,7 @@ function Feed() { return feed } - }) + })) ... } @@ -408,8 +402,8 @@ const articleRoute = new Route({ path: 'article', beforeLoad: () => { return { - articleQueryOptions: { queryKey: ['article'], queryFn: fetchArticle }, - commentsQueryOptions: { queryKey: ['comments'], queryFn: fetchComments }, + articleQueryOptions: queryOptions({ queryKey: ['article'], queryFn: fetchArticle }), + commentsQueryOptions: queryOptions({ queryKey: ['comments'], queryFn: fetchComments }), } }, loader: async ({ @@ -417,12 +411,12 @@ const articleRoute = new Route({ routeContext: { articleQueryOptions, commentsQueryOptions }, }) => { // Fetch comments asap, but don't block or throw errors - void queryClient.query(commentsQueryOptions).catch(noop) + void query(queryClient, commentsQueryOptions).catch(noop) // Don't render the route at all until article has been fetched // As this is critical data we want the error component to trigger // as soon as possible if something goes wrong - await queryClient.query({ + await query(queryClient, { ...articleQueryOptions, // If we have the article loaded already, we don't want to block on // an extra prefetch; fallback on the default useQuery behavior to @@ -449,12 +443,12 @@ Integration with other routers is also possible, see the [contacts-react-router] ## Manually Priming a Query -If you already have the data for your query synchronously available, you don't need to prefetch it. You can just use the [Query Client's `setQueryData` method](../reference/classes/QueryClient.md#setquerydata) to directly add or update a query's cached result by key. +If you already have the data for your query synchronously available, you don't need to prefetch it. You can just use the [`setQueryData` operation](./migrating-to-v6.md#client-operations-across-frameworks) to directly add or update a query's cached result by key. [//]: # 'ExampleManualPriming' ```tsx -queryClient.setQueryData(['todos'], todos) +setQueryData(queryClient, ['todos'], todos) ``` [//]: # 'ExampleManualPriming' diff --git a/docs/framework/react/guides/queries.md b/docs/framework/react/guides/queries.md index 09787da67eb..a55da5c8779 100644 --- a/docs/framework/react/guides/queries.md +++ b/docs/framework/react/guides/queries.md @@ -9,7 +9,7 @@ A query is a declarative dependency on an asynchronous source of data that is ti [//]: # 'SubscribeDescription' -To subscribe to a query in your components or custom hooks, call the `useQuery` hook with at least: +To subscribe to a query in your components or custom hooks, pass prepared options to `useQuery`. Define the following in `queryOptions`: [//]: # 'SubscribeDescription' @@ -21,10 +21,12 @@ To subscribe to a query in your components or custom hooks, call the `useQuery` [//]: # 'Example' ```tsx -import { useQuery } from '@tanstack/react-query' +import { queryOptions, useQuery } from '@tanstack/react-query' function App() { - const info = useQuery({ queryKey: ['todos'], queryFn: fetchTodoList }) + const info = useQuery( + queryOptions({ queryKey: ['todos'], queryFn: fetchTodoList }), + ) } ``` @@ -37,7 +39,9 @@ The query result returned by `useQuery` contains all of the information about th [//]: # 'Example2' ```tsx -const result = useQuery({ queryKey: ['todos'], queryFn: fetchTodoList }) +const result = useQuery( + queryOptions({ queryKey: ['todos'], queryFn: fetchTodoList }), +) ``` [//]: # 'Example2' @@ -59,24 +63,33 @@ For **most** queries, it's usually sufficient to check for the `isPending` state [//]: # 'Example3' ```tsx +import { + isError, + isPending, + queryOptions, + useQuery, +} from '@tanstack/react-query' + function Todos() { - const { isPending, isError, data, error } = useQuery({ - queryKey: ['todos'], - queryFn: fetchTodoList, - }) + const todos = useQuery( + queryOptions({ + queryKey: ['todos'], + queryFn: fetchTodoList, + }), + ) - if (isPending) { + if (isPending(todos)) { return Loading... } - if (isError) { - return Error: {error.message} + if (isError(todos)) { + return Error: {todos.error.message} } - // We can assume by this point that `isSuccess === true` + // The remaining result has defined data. return (
    - {data.map((todo) => ( + {todos.data.map((todo) => (
  • {todo.title}
  • ))}
@@ -92,10 +105,12 @@ If booleans aren't your thing, you can always use the `status` state as well: ```tsx function Todos() { - const { status, data, error } = useQuery({ - queryKey: ['todos'], - queryFn: fetchTodoList, - }) + const { status, data, error } = useQuery( + queryOptions({ + queryKey: ['todos'], + queryFn: fetchTodoList, + }), + ) if (status === 'pending') { return Loading... diff --git a/docs/framework/react/guides/query-cancellation.md b/docs/framework/react/guides/query-cancellation.md index fd32ce3d963..27b9c8d6f92 100644 --- a/docs/framework/react/guides/query-cancellation.md +++ b/docs/framework/react/guides/query-cancellation.md @@ -18,26 +18,28 @@ However, if you consume the `AbortSignal`, the Promise will be cancelled (e.g. a [//]: # 'Example' ```tsx -const query = useQuery({ - queryKey: ['todos'], - queryFn: async ({ signal }) => { - const todosResponse = await fetch('/todos', { - // Pass the signal to one fetch - signal, - }) - const todos = await todosResponse.json() - - const todoDetails = todos.map(async ({ details }) => { - const response = await fetch(details, { - // Or pass it to several +const query = useQuery( + queryOptions({ + queryKey: ['todos'], + queryFn: async ({ signal }) => { + const todosResponse = await fetch('/todos', { + // Pass the signal to one fetch signal, }) - return response.json() - }) + const todos = await todosResponse.json() + + const todoDetails = todos.map(async ({ details }) => { + const response = await fetch(details, { + // Or pass it to several + signal, + }) + return response.json() + }) - return Promise.all(todoDetails) - }, -}) + return Promise.all(todoDetails) + }, + }), +) ``` [//]: # 'Example' @@ -49,14 +51,16 @@ const query = useQuery({ ```tsx import axios from 'axios' -const query = useQuery({ - queryKey: ['todos'], - queryFn: ({ signal }) => - axios.get('/todos', { - // Pass the signal to `axios` - signal, - }), -}) +const query = useQuery( + queryOptions({ + queryKey: ['todos'], + queryFn: ({ signal }) => + axios.get('/todos', { + // Pass the signal to `axios` + signal, + }), + }), +) ``` [//]: # 'Example2' @@ -68,26 +72,28 @@ const query = useQuery({ ```tsx import axios from 'axios' -const query = useQuery({ - queryKey: ['todos'], - queryFn: ({ signal }) => { - // Create a new CancelToken source for this request - const CancelToken = axios.CancelToken - const source = CancelToken.source() - - const promise = axios.get('/todos', { - // Pass the source token to your request - cancelToken: source.token, - }) - - // Cancel the request if TanStack Query signals to abort - signal?.addEventListener('abort', () => { - source.cancel('Query was cancelled by TanStack Query') - }) - - return promise - }, -}) +const query = useQuery( + queryOptions({ + queryKey: ['todos'], + queryFn: ({ signal }) => { + // Create a new CancelToken source for this request + const CancelToken = axios.CancelToken + const source = CancelToken.source() + + const promise = axios.get('/todos', { + // Pass the source token to your request + cancelToken: source.token, + }) + + // Cancel the request if TanStack Query signals to abort + signal?.addEventListener('abort', () => { + source.cancel('Query was cancelled by TanStack Query') + }) + + return promise + }, + }), +) ``` [//]: # 'Example3' @@ -97,23 +103,25 @@ const query = useQuery({ [//]: # 'Example4' ```tsx -const query = useQuery({ - queryKey: ['todos'], - queryFn: ({ signal }) => { - return new Promise((resolve, reject) => { - var oReq = new XMLHttpRequest() - oReq.addEventListener('load', () => { - resolve(JSON.parse(oReq.responseText)) - }) - signal?.addEventListener('abort', () => { - oReq.abort() - reject() +const query = useQuery( + queryOptions({ + queryKey: ['todos'], + queryFn: ({ signal }) => { + return new Promise((resolve, reject) => { + var oReq = new XMLHttpRequest() + oReq.addEventListener('load', () => { + resolve(JSON.parse(oReq.responseText)) + }) + signal?.addEventListener('abort', () => { + oReq.abort() + reject() + }) + oReq.open('GET', '/todos') + oReq.send() }) - oReq.open('GET', '/todos') - oReq.send() - }) - }, -}) + }, + }), +) ``` [//]: # 'Example4' @@ -127,12 +135,14 @@ An `AbortSignal` can be set in the client `request` method. ```tsx const client = new GraphQLClient(endpoint) -const query = useQuery({ - queryKey: ['todos'], - queryFn: ({ signal }) => { - client.request({ document: query, signal }) - }, -}) +const query = useQuery( + queryOptions({ + queryKey: ['todos'], + queryFn: ({ signal }) => { + client.request({ document: query, signal }) + }, + }), +) ``` [//]: # 'Example5' @@ -144,33 +154,37 @@ An `AbortSignal` can be set in the `GraphQLClient` constructor. [//]: # 'Example6' ```tsx -const query = useQuery({ - queryKey: ['todos'], - queryFn: ({ signal }) => { - const client = new GraphQLClient(endpoint, { - signal, - }) - return client.request(query, variables) - }, -}) +const query = useQuery( + queryOptions({ + queryKey: ['todos'], + queryFn: ({ signal }) => { + const client = new GraphQLClient(endpoint, { + signal, + }) + return client.request(query, variables) + }, + }), +) ``` [//]: # 'Example6' ## Manual Cancellation -You might want to cancel a query manually. For example, if the request takes a long time to finish, you can allow the user to click a cancel button to stop the request. To do this, you just need to call `queryClient.cancelQueries({ queryKey })`, which will cancel the query and revert it back to its previous state. If you have consumed the `signal` passed to the query function, TanStack Query will additionally also cancel the Promise. +You might want to cancel a query manually. For example, if the request takes a long time to finish, you can allow the user to click a cancel button to stop the request. To do this, you just need to call `cancelQueries(queryClient, { queryKey })`, which will cancel the query and revert it back to its previous state. If you have consumed the `signal` passed to the query function, TanStack Query will additionally also cancel the Promise. [//]: # 'Example7' ```tsx -const query = useQuery({ - queryKey: ['todos'], - queryFn: async ({ signal }) => { - const resp = await fetch('/todos', { signal }) - return resp.json() - }, -}) +const query = useQuery( + queryOptions({ + queryKey: ['todos'], + queryFn: async ({ signal }) => { + const resp = await fetch('/todos', { signal }) + return resp.json() + }, + }), +) const queryClient = useQueryClient() @@ -178,7 +192,7 @@ return (
diff --git a/examples/lit/basic-graphql-request/src/post-list.ts b/examples/lit/basic-graphql-request/src/post-list.ts index db3d465056e..bc545301e0b 100644 --- a/examples/lit/basic-graphql-request/src/post-list.ts +++ b/examples/lit/basic-graphql-request/src/post-list.ts @@ -1,4 +1,11 @@ -import { createQueryController, useQueryClient } from '@tanstack/lit-query' +import { + createQueryController, + getQueryData, + isError, + isFetching, + isPending, + useQueryClient, +} from '@tanstack/lit-query' import { LitElement, html } from 'lit' import { styleMap } from 'lit/directives/style-map.js' import { postsQueries } from './services/posts/queries' @@ -16,26 +23,27 @@ class PostList extends LitElement { render() { const queryClient = useQueryClient() - const { isPending, isError, isFetching, data, error } = this.posts() + const queryResult = this.posts() return html`

Posts

${ - isPending + isPending(queryResult) ? html`
Loading...
` - : isError - ? html`Error: ${error.message}` + : isError(queryResult) + ? html`Error: ${queryResult.error.message}` : html` diff --git a/examples/lit/basic/src/basic-query.ts b/examples/lit/basic/src/basic-query.ts index bfe86230f46..c03e116c301 100644 --- a/examples/lit/basic/src/basic-query.ts +++ b/examples/lit/basic/src/basic-query.ts @@ -2,6 +2,8 @@ import { QueryClient, QueryClientProvider, createQueryController, + isError, + isPending, } from '@tanstack/lit-query' import { LitElement, html } from 'lit' import { resetTodoApi } from './services/todos/api' @@ -51,12 +53,12 @@ class BasicQueryExample extends LitElement { ${ - query.isPending + isPending(query) ? html`

Loading...

` : null } ${ - query.isError + isError(query) ? html`

Error: ${query.error.message}

` diff --git a/examples/lit/basic/src/lifecycle-contract.ts b/examples/lit/basic/src/lifecycle-contract.ts index e5e9b432761..c5b0caf7043 100644 --- a/examples/lit/basic/src/lifecycle-contract.ts +++ b/examples/lit/basic/src/lifecycle-contract.ts @@ -2,6 +2,7 @@ import { QueryClient, QueryClientProvider, createQueryController, + setQueryData, } from '@tanstack/lit-query' import { LitElement, html } from 'lit' @@ -25,7 +26,7 @@ function createContractClient(data: ContractProbeData): QueryClient { }, }) - client.setQueryData(contractQueryKey, data) + setQueryData(client, contractQueryKey, data) return client } diff --git a/examples/lit/basic/src/main.ts b/examples/lit/basic/src/main.ts index b65a96660a0..e9574284d47 100644 --- a/examples/lit/basic/src/main.ts +++ b/examples/lit/basic/src/main.ts @@ -3,6 +3,10 @@ import { QueryClientProvider, createMutationController, createQueryController, + invalidateQueries, + isError, + resetQueries, + setQueryData, useIsFetching, useIsMutating, } from '@tanstack/lit-query' @@ -55,7 +59,8 @@ class TanstackLitQueryDemo extends LitElement { private readonly createTodoMutation = createMutationController(this, { ...todosMutations.create(), onSuccess: (createdTodo) => { - demoQueryClient.setQueryData( + setQueryData( + demoQueryClient, todosQueries.list().queryKey, (existing) => { if (!existing) { @@ -104,7 +109,7 @@ class TanstackLitQueryDemo extends LitElement { } private async invalidateTodos(): Promise { - await demoQueryClient.invalidateQueries({ queryKey: todosQueries.all() }) + await invalidateQueries(demoQueryClient, { queryKey: todosQueries.all() }) } private seedCacheOnlyTodo(): void { @@ -115,7 +120,8 @@ class TanstackLitQueryDemo extends LitElement { title: `Seeded cache todo ${this.cacheSeedCount}`, } - demoQueryClient.setQueryData( + setQueryData( + demoQueryClient, todosQueries.list().queryKey, (existing) => { if (!existing) { @@ -148,7 +154,7 @@ class TanstackLitQueryDemo extends LitElement { this.cacheSeedCount = 0 this.nextTodoTitle = 'Add mutation assertion' - await demoQueryClient.resetQueries({ queryKey: todosQueries.all() }) + await resetQueries(demoQueryClient, { queryKey: todosQueries.all() }) this.createTodoMutation.reset() } @@ -230,7 +236,7 @@ class TanstackLitQueryDemo extends LitElement { ${ - query.isError + isError(query) ? html`
${query.error.message}
` : null } diff --git a/examples/lit/basic/src/mutation.ts b/examples/lit/basic/src/mutation.ts index ec206e8feb2..33aed7584a9 100644 --- a/examples/lit/basic/src/mutation.ts +++ b/examples/lit/basic/src/mutation.ts @@ -3,6 +3,7 @@ import { QueryClientProvider, createMutationController, createQueryController, + setQueryData, } from '@tanstack/lit-query' import { LitElement, html } from 'lit' import { resetTodoApi } from './services/todos/api' @@ -43,7 +44,8 @@ class MutationExample extends LitElement { private readonly addTodo = createMutationController(this, { ...todosMutations.create(), onSuccess: (created) => { - queryClient.setQueryData( + setQueryData( + queryClient, todosQueries.list().queryKey, (existing) => { if (!existing) { diff --git a/examples/lit/chat/src/chat-message.ts b/examples/lit/chat/src/chat-message.ts index e0cb720ab57..1ca28a56f6e 100644 --- a/examples/lit/chat/src/chat-message.ts +++ b/examples/lit/chat/src/chat-message.ts @@ -1,4 +1,4 @@ -import { createQueryController } from '@tanstack/lit-query' +import { createQueryController, isFetching } from '@tanstack/lit-query' import { LitElement, html } from 'lit' import { messagesQueries } from './services/messages/queries' import './message-bubble' @@ -21,9 +21,10 @@ class ChatMessage extends LitElement { } render() { - const { error, data, isFetching } = this.message() + const queryResult = this.message() - if (error) return html`An error has occurred: ${error.message}` + if (queryResult.error) + return html`An error has occurred: ${queryResult.error.message}` return html`
@@ -31,8 +32,8 @@ class ChatMessage extends LitElement { .message=${{ content: this.question, isQuestion: true }} >
` diff --git a/examples/lit/default-query-function/src/post-detail.ts b/examples/lit/default-query-function/src/post-detail.ts index 74b02ec35af..05d9b304742 100644 --- a/examples/lit/default-query-function/src/post-detail.ts +++ b/examples/lit/default-query-function/src/post-detail.ts @@ -1,4 +1,10 @@ -import { createQueryController, defaultQueryFn } from '@tanstack/lit-query' +import { + createQueryController, + defaultQueryFn, + isError, + isFetching, + isPending, +} from '@tanstack/lit-query' import { LitElement, html } from 'lit' import type { Post } from './types' @@ -25,7 +31,7 @@ class PostDetail extends LitElement { } render() { - const { isPending, isError, isFetching, data, error } = this.post() + const queryResult = this.post() return html`
${ - !this.postId || isPending + !this.postId || isPending(queryResult) ? html`
Loading...
` - : isError - ? html`Error: ${error.message}` + : isError(queryResult) + ? html`Error: ${queryResult.error.message}` : html` -

${data.title}

+

${queryResult.data.title}

-

${data.body}

+

${queryResult.data.body}

+
+
+ ${isFetching(queryResult) ? 'Background Updating...' : ' '}
-
${isFetching ? 'Background Updating...' : ' '}
` }
diff --git a/examples/lit/default-query-function/src/post-list.ts b/examples/lit/default-query-function/src/post-list.ts index ab9d78807af..eba8c250140 100644 --- a/examples/lit/default-query-function/src/post-list.ts +++ b/examples/lit/default-query-function/src/post-list.ts @@ -1,6 +1,10 @@ import { createQueryController, defaultQueryFn, + getQueryData, + isError, + isFetching, + isPending, useQueryClient, } from '@tanstack/lit-query' import { LitElement, html } from 'lit' @@ -23,26 +27,26 @@ class PostList extends LitElement { render() { const queryClient = useQueryClient() - const { isPending, isError, isFetching, data, error } = this.posts() + const queryResult = this.posts() return html`

Posts

${ - isPending + isPending(queryResult) ? html`
Loading...
` - : isError - ? html`Error: ${error.message}` + : isError(queryResult) + ? html`Error: ${queryResult.error.message}` : html` diff --git a/examples/lit/infinite-query-with-max-pages/src/main.ts b/examples/lit/infinite-query-with-max-pages/src/main.ts index 42b979c9718..f4d533e082b 100644 --- a/examples/lit/infinite-query-with-max-pages/src/main.ts +++ b/examples/lit/infinite-query-with-max-pages/src/main.ts @@ -2,6 +2,9 @@ import { QueryClient, QueryClientProvider, createInfiniteQueryController, + isFetching, + isFetchingNextPage, + isFetchingPreviousPage, } from '@tanstack/lit-query' import { LitElement, html } from 'lit' import { worker } from './mocks' @@ -27,37 +30,29 @@ class InfiniteQueryExample extends LitElement { } private renderProjects() { - const { - status, - data, - error, - isFetching, - isFetchingNextPage, - isFetchingPreviousPage, - hasNextPage, - hasPreviousPage, - } = this.projects() + const queryResult = this.projects() - if (status === 'pending') return html`

Loading...

` - if (status === 'error') return html`Error: ${error.message}` + if (queryResult.status === 'pending') return html`

Loading...

` + if (queryResult.status === 'error') + return html`Error: ${queryResult.error.message}` return html`
- ${data.pages.map((page) => + ${queryResult.data.pages.map((page) => page.data.map( (project) => html`

this.projects.fetchNextPage()} - ?disabled=${!hasNextPage || isFetchingNextPage} + ?disabled=${!queryResult.hasNextPage || isFetchingNextPage(queryResult)} > ${ - isFetchingNextPage + isFetchingNextPage(queryResult) ? 'Loading more...' - : hasNextPage + : queryResult.hasNextPage ? 'Load Newer' : 'Nothing more to load' }

- ${isFetching && !isFetchingNextPage ? 'Background Updating...' : null} + ${isFetching(queryResult) && !isFetchingNextPage(queryResult) ? 'Background Updating...' : null}
` } diff --git a/examples/lit/load-more-infinite-scroll-lit-labs-router/src/example-view.ts b/examples/lit/load-more-infinite-scroll-lit-labs-router/src/example-view.ts index 057fc071e9d..fa5fa69d9ab 100644 --- a/examples/lit/load-more-infinite-scroll-lit-labs-router/src/example-view.ts +++ b/examples/lit/load-more-infinite-scroll-lit-labs-router/src/example-view.ts @@ -1,4 +1,9 @@ -import { createInfiniteQueryController } from '@tanstack/lit-query' +import { + createInfiniteQueryController, + isFetching, + isFetchingNextPage, + isFetchingPreviousPage, +} from '@tanstack/lit-query' import { LitElement, html } from 'lit' import { ref } from 'lit/directives/ref.js' import { projectsQueries } from './services/projects/queries' @@ -26,9 +31,13 @@ class ExampleView extends LitElement { } protected override updated() { - const { hasNextPage, isFetchingNextPage } = this.projects() + const queryResult = this.projects() - if (this.inView && hasNextPage && !isFetchingNextPage) { + if ( + this.inView && + queryResult.hasNextPage && + !isFetchingNextPage(queryResult) + ) { this.projects.fetchNextPage() } } @@ -45,37 +54,29 @@ class ExampleView extends LitElement { } private renderProjects() { - const { - status, - data, - error, - isFetching, - isFetchingNextPage, - isFetchingPreviousPage, - hasNextPage, - hasPreviousPage, - } = this.projects() + const detailQuery = this.projects() - if (status === 'pending') return html`

Loading...

` - if (status === 'error') return html`Error: ${error.message}` + if (detailQuery.status === 'pending') return html`

Loading...

` + if (detailQuery.status === 'error') + return html`Error: ${detailQuery.error.message}` return html`
- ${data.pages.map((page) => + ${detailQuery.data.pages.map((page) => page.data.map( (project) => html`

this.projects.fetchNextPage()} - ?disabled=${!hasNextPage || isFetchingNextPage} + ?disabled=${!detailQuery.hasNextPage || isFetchingNextPage(detailQuery)} > ${ - isFetchingNextPage + isFetchingNextPage(detailQuery) ? 'Loading more...' - : hasNextPage + : detailQuery.hasNextPage ? 'Load Newer' : 'Nothing more to load' }

- ${isFetching && !isFetchingNextPage ? 'Background Updating...' : null} + ${isFetching(detailQuery) && !isFetchingNextPage(detailQuery) ? 'Background Updating...' : null}
` } diff --git a/examples/lit/offline-lit-labs-router/src/main.ts b/examples/lit/offline-lit-labs-router/src/main.ts index 34f4a71869f..bdec6fe2b7d 100644 --- a/examples/lit/offline-lit-labs-router/src/main.ts +++ b/examples/lit/offline-lit-labs-router/src/main.ts @@ -1,5 +1,13 @@ import { Router } from '@lit-labs/router' -import { QueryClientProvider, noop, onlineManager } from '@tanstack/lit-query' +import { + QueryClientProvider, + getQueryData, + invalidateQueries, + noop, + onlineManager, + query, + resumePausedMutations, +} from '@tanstack/lit-query' import { persistQueryClient } from '@tanstack/query-persist-client-core' import { LitElement, html } from 'lit' import { worker } from './mocks' @@ -32,12 +40,12 @@ class OfflineApp extends LitElement { path: '/:movieId', enter: async ({ movieId = '' }) => { if ( - !queryClient.getQueryData(moviesQueries.detail(movieId).queryKey) && + !getQueryData(queryClient, moviesQueries.detail(movieId).queryKey) && // do not load if we are offline because it returns a promise that is pending until we go online again // we just let the movie-detail-view element handle it onlineManager.isOnline() ) { - await queryClient.query(moviesQueries.detail(movieId)).catch(noop) + await query(queryClient, moviesQueries.detail(movieId)).catch(noop) } return true }, @@ -85,8 +93,8 @@ worker.start().then(async () => { const [, restorePromise] = persistQueryClient({ queryClient, persister }) await restorePromise // resume mutations after initial restore from localStorage was successful - queryClient.resumePausedMutations().then(() => { - queryClient.invalidateQueries() + resumePausedMutations(queryClient).then(() => { + invalidateQueries(queryClient) }) customElements.define('offline-app', OfflineApp) }) diff --git a/examples/lit/offline-lit-labs-router/src/movie-detail-view.ts b/examples/lit/offline-lit-labs-router/src/movie-detail-view.ts index 04a8c9187b0..f9d53371f5f 100644 --- a/examples/lit/offline-lit-labs-router/src/movie-detail-view.ts +++ b/examples/lit/offline-lit-labs-router/src/movie-detail-view.ts @@ -1,6 +1,14 @@ import { + cancelQueries, createMutationController, createQueryController, + getQueryData, + invalidateQueries, + isError, + isFetching, + isLoading, + isPaused, + setQueryData, } from '@tanstack/lit-query' import { LitElement, html } from 'lit' import { moviesMutations, moviesQueries } from './services/movies/queries' @@ -22,16 +30,17 @@ class MovieDetailView extends LitElement { ...moviesMutations.update(), mutationKey: moviesQueries.detail(this.movieId).queryKey, onMutate: async (variables, { client }) => { - await client.cancelQueries({ + await cancelQueries(client, { queryKey: moviesQueries.detail(this.movieId).queryKey, }) const { queryKey } = moviesQueries.detail(this.movieId) - const previousData = client.getQueryData(queryKey) + const previousData = getQueryData(client, queryKey) // remove local state so that server state is taken instead this.commentDraft = undefined - client.setQueryData( + setQueryData( + client, queryKey, (old) => old && { @@ -46,13 +55,14 @@ class MovieDetailView extends LitElement { return { previousData } }, onError: (_, __, onMutateResult, { client }) => { - client.setQueryData( + setQueryData( + client, moviesQueries.detail(this.movieId).queryKey, onMutateResult?.previousData, ) }, onSettled: (_, __, ___, ____, { client }) => { - client.invalidateQueries({ + invalidateQueries(client, { queryKey: moviesQueries.detail(this.movieId).queryKey, }) }, @@ -82,20 +92,18 @@ class MovieDetailView extends LitElement { } render() { - const { data, error, isError, isFetching, isLoading, isPaused } = - this.movie() - const { isPaused: isMutationPaused, isPending: isMutationPending } = - this.updateMovie() + const queryResult = this.movie() + const updateMovie = this.updateMovie() - if (isLoading) { + if (isLoading(queryResult)) { return 'Loading...' } - if (data) { + if (queryResult.data) { return html`
Back -

Movie: ${data.movie.title}

+

Movie: ${queryResult.data.movie.title}

Try to mock offline behavior with the button above, then update the comment. The optimistic update will succeed, but the actual mutation @@ -119,13 +127,15 @@ class MovieDetailView extends LitElement {

-
Updated at: ${new Date(data.ts).toLocaleTimeString()}
-
${isFetching ? 'fetching...' : ''}
+
+ Updated at: ${new Date(queryResult.data.ts).toLocaleTimeString()} +
+
${isFetching(queryResult) ? 'fetching...' : ''}
${ - isMutationPaused + updateMovie.isPaused ? 'mutation paused - offline' - : isMutationPending + : updateMovie.isPending ? 'updating...' : '' } @@ -134,17 +144,17 @@ class MovieDetailView extends LitElement { ` } - if (isError) { + if (isError(queryResult)) { return html`
Back

Couldn't load movie!

-
${error.message}
+
${queryResult.error.message}
` } - if (isPaused) { + if (isPaused(queryResult)) { return "We're offline and have no data to show :(" } diff --git a/examples/lit/offline-lit-labs-router/src/movie-list-view.ts b/examples/lit/offline-lit-labs-router/src/movie-list-view.ts index 0cd20c3cdcb..3e01577395d 100644 --- a/examples/lit/offline-lit-labs-router/src/movie-list-view.ts +++ b/examples/lit/offline-lit-labs-router/src/movie-list-view.ts @@ -1,4 +1,9 @@ -import { createQueryController } from '@tanstack/lit-query' +import { + createQueryController, + isError, + isFetching, + isLoading, +} from '@tanstack/lit-query' import { LitElement, html } from 'lit' import { moviesQueries } from './services/movies/queries' @@ -10,13 +15,13 @@ class MovieListView extends LitElement { } render() { - const { data, error, isError, isFetching, isLoading } = this.movies() + const queryResult = this.movies() - if (isLoading) { + if (isLoading(queryResult)) { return 'Loading...' } - if (data) { + if (queryResult.data) { return html`

Movies

@@ -26,22 +31,24 @@ class MovieListView extends LitElement { refetch as soon as you go online again.

    - ${data.movies.map( + ${queryResult.data.movies.map( (movie) => html`
  • ${movie.title}
  • `, )}
-
Updated at: ${new Date(data.ts).toLocaleTimeString()}
-
${isFetching ? 'fetching...' : ''}
+
+ Updated at: ${new Date(queryResult.data.ts).toLocaleTimeString()} +
+
${isFetching(queryResult) ? 'fetching...' : ''}
` } - if (isError) { + if (isError(queryResult)) { return html`

Couldn't load movies!

-
${error.message}
+
${queryResult.error.message}
` } diff --git a/examples/lit/offline-lit-labs-router/src/queryClient.ts b/examples/lit/offline-lit-labs-router/src/queryClient.ts index 1ba92dd50f0..f92655c0051 100644 --- a/examples/lit/offline-lit-labs-router/src/queryClient.ts +++ b/examples/lit/offline-lit-labs-router/src/queryClient.ts @@ -1,4 +1,8 @@ -import { MutationCache, QueryClient } from '@tanstack/lit-query' +import { + MutationCache, + QueryClient, + setMutationDefaults, +} from '@tanstack/lit-query' import { createAsyncStoragePersister } from '@tanstack/query-async-storage-persister' import { moviesMutations, moviesQueries } from './services/movies/queries' import { toast } from './toast' @@ -24,7 +28,7 @@ export const queryClient = new QueryClient({ }) // we need a default mutation function so that paused mutations can resume after a page reload -queryClient.setMutationDefaults(moviesQueries.all(), { +setMutationDefaults(queryClient, moviesQueries.all(), { ...moviesMutations.update(), onSuccess: (data) => { toast.success(data.message) diff --git a/examples/lit/offline-lit-labs-router/src/services/movies/queries.ts b/examples/lit/offline-lit-labs-router/src/services/movies/queries.ts index 8b011990a71..e19d14229cf 100644 --- a/examples/lit/offline-lit-labs-router/src/services/movies/queries.ts +++ b/examples/lit/offline-lit-labs-router/src/services/movies/queries.ts @@ -1,4 +1,8 @@ -import { mutationOptions, queryOptions } from '@tanstack/lit-query' +import { + cancelQueries, + mutationOptions, + queryOptions, +} from '@tanstack/lit-query' import { moviesAPI } from './api' export const moviesQueries = { @@ -23,7 +27,7 @@ export const moviesMutations = { context, ) => { // to avoid clashes with our optimistic update when an offline mutation continues - await context.client.cancelQueries({ + await cancelQueries(context.client, { queryKey: moviesQueries.detail(id).queryKey, }) return moviesAPI.updateMovie(id, comment) diff --git a/examples/lit/optimistic-updates/src/todo-list-cache.ts b/examples/lit/optimistic-updates/src/todo-list-cache.ts index 32c32d6f049..ddbccb7d119 100644 --- a/examples/lit/optimistic-updates/src/todo-list-cache.ts +++ b/examples/lit/optimistic-updates/src/todo-list-cache.ts @@ -1,6 +1,10 @@ import { + cancelQueries, createMutationController, createQueryController, + getQueryData, + invalidateQueries, + setQueryData, } from '@tanstack/lit-query' import { LitElement, html } from 'lit' import { todosMutations, todosQueries } from './services/todos/queries' @@ -31,11 +35,11 @@ class TodoListCache extends LitElement { ...todosMutations.create(), onMutate: async (text, { client }) => { this.lastError = null - await client.cancelQueries({ + await cancelQueries(client, { queryKey: todosQueries.list().queryKey, }) - const previousTodos = client.getQueryData(todosQueries.list().queryKey) + const previousTodos = getQueryData(client, todosQueries.list().queryKey) const optimisticId = `optimistic-${Date.now()}` const optimisticTodo: Todo = { @@ -44,7 +48,7 @@ class TodoListCache extends LitElement { createdAt: Date.now(), } - client.setQueryData(todosQueries.list().queryKey, (old = []) => [ + setQueryData(client, todosQueries.list().queryKey, (old = []) => [ ...old, optimisticTodo, ]) @@ -54,15 +58,19 @@ class TodoListCache extends LitElement { onError: (_err, _text, context, { client }) => { this.lastError = _err.message if (context?.previousTodos !== undefined) { - client.setQueryData(todosQueries.list().queryKey, context.previousTodos) + setQueryData( + client, + todosQueries.list().queryKey, + context.previousTodos, + ) } else if (context?.optimisticId) { - client.setQueryData(todosQueries.list().queryKey, (old = []) => + setQueryData(client, todosQueries.list().queryKey, (old = []) => old.filter((todo) => todo.id !== context.optimisticId), ) } }, onSettled: (_data, _error, _variables, _context, { client }) => - client.invalidateQueries({ queryKey: todosQueries.list().queryKey }), + invalidateQueries(client, { queryKey: todosQueries.list().queryKey }), })) protected override createRenderRoot(): HTMLElement | DocumentFragment { diff --git a/examples/lit/optimistic-updates/src/todo-list-ui.ts b/examples/lit/optimistic-updates/src/todo-list-ui.ts index 5161049f69a..2617caee9a4 100644 --- a/examples/lit/optimistic-updates/src/todo-list-ui.ts +++ b/examples/lit/optimistic-updates/src/todo-list-ui.ts @@ -1,6 +1,7 @@ import { createMutationController, createQueryController, + invalidateQueries, } from '@tanstack/lit-query' import { LitElement, html } from 'lit' import { todosMutations, todosQueries } from './services/todos/queries' @@ -17,7 +18,7 @@ class TodoListUI extends LitElement { private readonly addTodoMutation = createMutationController(this, () => ({ ...todosMutations.create(), onSettled: (_data, _error, _variables, _onMutateResult, { client }) => - client.invalidateQueries({ queryKey: todosQueries.list().queryKey }), + invalidateQueries(client, { queryKey: todosQueries.list().queryKey }), })) protected override createRenderRoot(): HTMLElement | DocumentFragment { diff --git a/examples/lit/pagination/src/main.ts b/examples/lit/pagination/src/main.ts index 79aa7616ddb..8d209e8ada5 100644 --- a/examples/lit/pagination/src/main.ts +++ b/examples/lit/pagination/src/main.ts @@ -1,10 +1,19 @@ import { QueryClient, QueryClientProvider, + cancelQueries, createMutationController, createQueryController, + getQueriesData, + invalidateQueries, + isError, + isFetching, keepPreviousData, noop, + placeholderData, + query as queryQuery, + resetQueries, + setQueryData, } from '@tanstack/lit-query' import { LitElement, html } from 'lit' import { @@ -108,7 +117,7 @@ class PaginationDemo extends LitElement { this.projectsQueryOptions = { ...projectsQueries.list(this.page, this.delayMs, this.forceErrorMode), - placeholderData: keepPreviousData, + placeholderData: placeholderData(keepPreviousData), } this.projectsQuery = createQueryController(this, this.projectsQueryOptions) @@ -128,7 +137,7 @@ class PaginationDemo extends LitElement { this.draftName = '' this.draftOwner = 'Team 6' this.syncProjectsQueryOptions() - await queryClient.invalidateQueries({ + await invalidateQueries(queryClient, { queryKey: projectsQueries.all(), refetchType: 'none', }) @@ -145,9 +154,9 @@ class PaginationDemo extends LitElement { onMutate: async (variables) => { this.mutationControlStatus = 'idle' this.mutationControlError = undefined - await queryClient.cancelQueries({ queryKey: projectsQueries.all() }) + await cancelQueries(queryClient, { queryKey: projectsQueries.all() }) - const snapshots = queryClient.getQueriesData({ + const snapshots = getQueriesData(queryClient, { queryKey: projectsQueries.all(), }) @@ -156,7 +165,7 @@ class PaginationDemo extends LitElement { continue } - queryClient.setQueryData(key, { + setQueryData(queryClient, key, { ...existing, projects: existing.projects.map((project) => project.id === variables.id @@ -170,11 +179,11 @@ class PaginationDemo extends LitElement { }, onError: (_error, _variables, onMutateResult) => { for (const [key, snapshot] of onMutateResult?.snapshots ?? []) { - queryClient.setQueryData(key, snapshot) + setQueryData(queryClient, key, snapshot) } }, onSettled: async () => { - await queryClient.invalidateQueries({ + await invalidateQueries(queryClient, { queryKey: projectsQueries.all(), }) }, @@ -254,11 +263,10 @@ class PaginationDemo extends LitElement { this.prefetchStatus = `pending:${targetPage}` try { - await queryClient - .query( - projectsQueries.list(targetPage, this.delayMs, this.forceErrorMode), - ) - .catch(noop) + await queryQuery( + queryClient, + projectsQueries.list(targetPage, this.delayMs, this.forceErrorMode), + ).catch(noop) this.prefetchStatus = `ready:${targetPage}` } catch (error) { this.prefetchStatus = `error:${String(error)}` @@ -312,7 +320,7 @@ class PaginationDemo extends LitElement { this.syncProjectsQueryOptions() this.createProjectMutation.reset() this.favoriteMutation.reset() - await queryClient.resetQueries({ queryKey: projectsQueries.all() }) + await resetQueries(queryClient, { queryKey: projectsQueries.all() }) await this.projectsQuery.refetch() } catch (error) { this.resetError = String(error) @@ -367,7 +375,7 @@ class PaginationDemo extends LitElement {
query: ${query.status}
- isFetching: ${query.isFetching ? 'yes' : 'no'} + isFetching: ${isFetching(query) ? 'yes' : 'no'}
isPlaceholderData: ${query.isPlaceholderData ? 'yes' : 'no'} @@ -395,7 +403,7 @@ class PaginationDemo extends LitElement {
${ - query.isError + isError(query) ? html`

${query.error.message}

` : null } diff --git a/examples/lit/playground/src/add-todo.ts b/examples/lit/playground/src/add-todo.ts index e62c04e9078..d1950628c85 100644 --- a/examples/lit/playground/src/add-todo.ts +++ b/examples/lit/playground/src/add-todo.ts @@ -1,4 +1,7 @@ -import { createMutationController } from '@tanstack/lit-query' +import { + createMutationController, + invalidateQueries, +} from '@tanstack/lit-query' import { LitElement, html } from 'lit' import { todosMutations, todosQueries } from './services/todos/queries' @@ -12,7 +15,7 @@ class AddTodo extends LitElement { private readonly addMutation = createMutationController(this, { ...todosMutations.create(), onSuccess: (_data, _variables, _onMutateResult, { client }) => { - client.invalidateQueries({ queryKey: todosQueries.lists() }) + invalidateQueries(client, { queryKey: todosQueries.lists() }) }, }) diff --git a/examples/lit/playground/src/edit-todo.ts b/examples/lit/playground/src/edit-todo.ts index dfc3e1320ff..32e7b1a3be7 100644 --- a/examples/lit/playground/src/edit-todo.ts +++ b/examples/lit/playground/src/edit-todo.ts @@ -1,6 +1,9 @@ import { createMutationController, createQueryController, + invalidateQueries, + isFetching, + setQueryData, } from '@tanstack/lit-query' import { LitElement, html } from 'lit' import { todosMutations, todosQueries } from './services/todos/queries' @@ -23,8 +26,12 @@ class EditTodo extends LitElement { ...todosMutations.update(), onSuccess: (todo, _variables, _onMutateResult, { client }) => { // Update `todos` and the individual todo queries when this mutation succeeds - client.invalidateQueries({ queryKey: todosQueries.lists() }) - client.setQueryData(todosQueries.detail(this.editingIndex).queryKey, todo) + invalidateQueries(client, { queryKey: todosQueries.lists() }) + setQueryData( + client, + todosQueries.detail(this.editingIndex).queryKey, + todo, + ) this.draft = {} }, }) @@ -40,20 +47,21 @@ class EditTodo extends LitElement { } render() { - const { status, data, isFetching, failureCount, refetch } = this.todo() + const queryResult = this.todo() const { status: saveStatus, error: saveError, mutate: save, } = this.saveMutation() - const disableEditSave = status === 'pending' || saveStatus === 'pending' + const disableEditSave = + queryResult.status === 'pending' || saveStatus === 'pending' return html`
${ - data + queryResult.data ? html` - Editing Todo "${data.name}" (#${this.editingIndex}) + Editing Todo "${queryResult.data.name}" + (#${this.editingIndex}) ` : null }
${ - status === 'pending' - ? html`Loading... (Attempt: ${failureCount + 1})` - : status === 'error' + queryResult.status === 'pending' + ? html`Loading... (Attempt: ${queryResult.failureCount + 1})` + : queryResult.status === 'error' ? html` Error! - @@ -82,7 +93,7 @@ class EditTodo extends LitElement {
${ - isFetching + isFetching(queryResult) ? html` Background Refreshing... (Attempt: - ${failureCount + 1}) + ${queryResult.failureCount + 1}) ` : html` ` } diff --git a/examples/lit/playground/src/main.ts b/examples/lit/playground/src/main.ts index 9b525f4ba44..c5c06117be5 100644 --- a/examples/lit/playground/src/main.ts +++ b/examples/lit/playground/src/main.ts @@ -1,4 +1,9 @@ -import { QueryClient, QueryClientProvider } from '@tanstack/lit-query' +import { + QueryClient, + QueryClientProvider, + invalidateQueries, + setDefaultOptions, +} from '@tanstack/lit-query' import { LitElement, html } from 'lit' import { keyed } from 'lit/directives/keyed.js' import { styleMap } from 'lit/directives/style-map.js' @@ -47,7 +52,7 @@ class PlaygroundApp extends LitElement { serverConfig.queryTimeMax = this.localFetchTimeMax if (changedProperties.has('staleTime') || changedProperties.has('gcTime')) { - queryClient.setDefaultOptions({ + setDefaultOptions(queryClient, { queries: { staleTime: this.staleTime, gcTime: this.gcTime, @@ -151,7 +156,7 @@ class PlaygroundApp extends LitElement {
diff --git a/examples/lit/playground/src/todo-list.ts b/examples/lit/playground/src/todo-list.ts index 322f443c680..ecbec3b4e60 100644 --- a/examples/lit/playground/src/todo-list.ts +++ b/examples/lit/playground/src/todo-list.ts @@ -1,4 +1,4 @@ -import { createQueryController } from '@tanstack/lit-query' +import { createQueryController, isFetching } from '@tanstack/lit-query' import { LitElement, html } from 'lit' import { todosQueries } from './services/todos/queries' @@ -26,8 +26,7 @@ class TodoList extends LitElement { } render() { - const { status, data, isFetching, error, failureCount, refetch } = - this.todos() + const queryResult = this.todos() return html`
@@ -42,21 +41,23 @@ class TodoList extends LitElement {
${ - status === 'pending' - ? html`Loading... (Attempt: ${failureCount + 1})` - : status === 'error' + queryResult.status === 'pending' + ? html`Loading... (Attempt: ${queryResult.failureCount + 1})` + : queryResult.status === 'error' ? html` - Error: ${error.message} + Error: ${queryResult.error.message}
-
` : html`
    - ${data.map( + ${queryResult.data.map( (todo) => html`
  • ${todo.name} @@ -72,10 +73,10 @@ class TodoList extends LitElement {
${ - isFetching + isFetching(queryResult) ? html` Background Refreshing... (Attempt: - ${failureCount + 1}) + ${queryResult.failureCount + 1}) ` : html` ` } diff --git a/examples/lit/prefetching-lit-labs-router/src/character-item.ts b/examples/lit/prefetching-lit-labs-router/src/character-item.ts index 0dc6e087e98..20fe3dc10e3 100644 --- a/examples/lit/prefetching-lit-labs-router/src/character-item.ts +++ b/examples/lit/prefetching-lit-labs-router/src/character-item.ts @@ -1,6 +1,7 @@ import { createQueryController, noop, + query, useQueryClient, } from '@tanstack/lit-query' import { LitElement, html } from 'lit' @@ -25,12 +26,10 @@ class CharacterItem extends LitElement { } private prefetch() { - useQueryClient() - .query({ - ...charactersQueries.detail(this.characterId), - staleTime: 10 * 1000, // only prefetch if older than 10 seconds - }) - .catch(noop) + query(useQueryClient(), { + ...charactersQueries.detail(this.characterId), + staleTime: 10 * 1000, // only prefetch if older than 10 seconds + }).catch(noop) } private selectCharacter() { diff --git a/examples/lit/prefetching-lit-labs-router/src/character-view.ts b/examples/lit/prefetching-lit-labs-router/src/character-view.ts index 7da422c013d..b9e8bd4f36f 100644 --- a/examples/lit/prefetching-lit-labs-router/src/character-view.ts +++ b/examples/lit/prefetching-lit-labs-router/src/character-view.ts @@ -1,4 +1,4 @@ -import { createQueryController } from '@tanstack/lit-query' +import { createQueryController, isFetching } from '@tanstack/lit-query' import { LitElement, html } from 'lit' import { charactersQueries } from './services/characters/queries' @@ -24,21 +24,22 @@ class CharacterView extends LitElement { } private renderCharacter() { - const { status, data, error, isFetching } = this.character() + const queryResult = this.character() if (!this.isValidId) return 'Invalid character ID' - if (status === 'pending') return 'Loading...' - if (status === 'error') return html`Error: ${error.message}` + if (queryResult.status === 'pending') return 'Loading...' + if (queryResult.status === 'error') + return html`Error: ${queryResult.error.message}` return html` -

${data.name}

+

${queryResult.data.name}

-

status: ${data.status}

-

species: ${data.species}

-

gender: ${data.gender}

-

origin: ${data.origin.name}

+

status: ${queryResult.data.status}

+

species: ${queryResult.data.species}

+

gender: ${queryResult.data.gender}

+

origin: ${queryResult.data.origin.name}

-
${isFetching ? 'Background Updating...' : ' '}
+
${isFetching(queryResult) ? 'Background Updating...' : ' '}
` } diff --git a/examples/lit/prefetching-lit-labs-router/src/home-view.ts b/examples/lit/prefetching-lit-labs-router/src/home-view.ts index aeab5fe9b12..8c037674409 100644 --- a/examples/lit/prefetching-lit-labs-router/src/home-view.ts +++ b/examples/lit/prefetching-lit-labs-router/src/home-view.ts @@ -1,4 +1,4 @@ -import { createQueryController } from '@tanstack/lit-query' +import { createQueryController, isError, isPending } from '@tanstack/lit-query' import { LitElement, html } from 'lit' import { charactersQueries } from './services/characters/queries' import './character-item' @@ -31,8 +31,8 @@ class HomeView extends LitElement { const charactersQuery = this.characters() const characterQuery = this.character() - if (charactersQuery.isPending) return 'Loading...' - if (charactersQuery.isError) { + if (isPending(charactersQuery)) return 'Loading...' + if (isError(charactersQuery)) { return html`Error: ${charactersQuery.error.message}` } @@ -51,9 +51,9 @@ class HomeView extends LitElement {

Selected Character

${ - characterQuery.isPending + isPending(characterQuery) ? 'Loading...' - : characterQuery.isError + : isError(characterQuery) ? html`Error: ${characterQuery.error.message}` : html`
${JSON.stringify(characterQuery.data, null, 2)}
` } diff --git a/examples/lit/simple/src/main.ts b/examples/lit/simple/src/main.ts index ad65714b760..19e2ebb9ff0 100644 --- a/examples/lit/simple/src/main.ts +++ b/examples/lit/simple/src/main.ts @@ -2,6 +2,8 @@ import { QueryClient, QueryClientProvider, createQueryController, + isFetching, + isPending, } from '@tanstack/lit-query' import { LitElement, html } from 'lit' import { reposQueries } from './services/repos/queries' @@ -23,19 +25,20 @@ class SimpleExample extends LitElement { } render() { - const { data, error, isFetching, isPending } = this.repo() + const queryResult = this.repo() - if (isPending) return html`Loading...` + if (isPending(queryResult)) return html`Loading...` - if (error) return html`An error has occurred: ${error.message}` + if (queryResult.error) + return html`An error has occurred: ${queryResult.error.message}` return html` -

${data.name}

-

${data.description}

- 👀 ${data.subscribers_count} - ✨ ${data.stargazers_count} - 🍴 ${data.forks_count} -
${isFetching ? 'Updating...' : ''}
+

${queryResult.data.name}

+

${queryResult.data.description}

+ 👀 ${queryResult.data.subscribers_count} + ✨ ${queryResult.data.stargazers_count} + 🍴 ${queryResult.data.forks_count} +
${isFetching(queryResult) ? 'Updating...' : ''}
` } } diff --git a/examples/lit/ssr/server/index.mjs b/examples/lit/ssr/server/index.mjs index 9c817db5835..fd80164ba32 100644 --- a/examples/lit/ssr/server/index.mjs +++ b/examples/lit/ssr/server/index.mjs @@ -5,6 +5,7 @@ import { setTimeout as sleep } from 'node:timers/promises' import { fileURLToPath } from 'node:url' import { render } from '@lit-labs/ssr' import { collectResult } from '@lit-labs/ssr/lib/render-result.js' +import { query } from '@tanstack/lit-query' import { QueryClient, dehydrate } from '@tanstack/lit-query' import { html } from 'lit' import { @@ -185,7 +186,7 @@ async function renderPage(res) { const queryClient = createBrowserQueryClient() resetSsrQueryControllerCreationCount(queryClient) const dataQueryOptions = dataQueries.detail(SSR_PUBLIC_ORIGIN) - await queryClient.query(dataQueryOptions).catch((error) => { + await query(queryClient, dataQueryOptions).catch((error) => { throw new Error( 'SSR prefetch did not complete successfully. Refusing to render loading HTML.', { cause: error }, diff --git a/examples/lit/ssr/src/app.ts b/examples/lit/ssr/src/app.ts index 637add57ee9..008b0998900 100644 --- a/examples/lit/ssr/src/app.ts +++ b/examples/lit/ssr/src/app.ts @@ -1,4 +1,9 @@ -import { createQueryController } from '@tanstack/lit-query' +import { + createQueryController, + isError, + isFetching, + isPending, +} from '@tanstack/lit-query' import { LitElement, css, html } from 'lit' import { dataQueries } from './services/data/queries.js' import type { QueryClient, QueryResultAccessor } from '@tanstack/lit-query' @@ -110,7 +115,7 @@ export class SsrApp extends LitElement { const query = this.dataQuery() - if (query.isPending) { + if (isPending(query)) { return html`

Lit Query SSR

@@ -119,7 +124,7 @@ export class SsrApp extends LitElement { ` } - if (query.isError) { + if (isError(query)) { return html`

Lit Query SSR

@@ -132,7 +137,9 @@ export class SsrApp extends LitElement { return html`

Lit Query SSR

-

${query.isFetching ? 'Refreshing' : 'Ready'}

+

+ ${isFetching(query) ? 'Refreshing' : 'Ready'} +

${query.data.message}

Request count: ${query.data.requestCount} @@ -140,7 +147,7 @@ export class SsrApp extends LitElement {

Served at: ${query.data.servedAt}

)} - {isFetchingNextPage && ( + {isFetchingNextPage(infiniteQueryResult) && (
Fetching next page...
)}
diff --git a/examples/preact/auto-refetching/src/App.tsx b/examples/preact/auto-refetching/src/App.tsx index eed797aff7e..6b89fc3cb51 100644 --- a/examples/preact/auto-refetching/src/App.tsx +++ b/examples/preact/auto-refetching/src/App.tsx @@ -1,4 +1,12 @@ -import { useMutation, useQuery, useQueryClient } from '@tanstack/preact-query' +import { + invalidateQueries, + isFetching, + queryOptions, + refetchInterval, + useMutation, + useQuery, + useQueryClient, +} from '@tanstack/preact-query' import { PreactQueryDevtools } from '@tanstack/preact-query-devtools' import { useState } from 'preact/hooks' import { todosMutations, todosQueries } from './services/todos/queries' @@ -8,26 +16,29 @@ export default function App() { const [intervalMs, setIntervalMs] = useState(1000) const [value, setValue] = useState('') - const { status, data, error, isFetching } = useQuery({ - ...todosQueries.list(), - // Refetch the data every second - refetchInterval: intervalMs, - }) + const queryResult = useQuery( + queryOptions({ + ...todosQueries.list(), + // Refetch the data every second + refetchInterval: refetchInterval(intervalMs), + }), + ) const addMutation = useMutation({ ...todosMutations.create(), onSuccess: () => - queryClient.invalidateQueries({ queryKey: todosQueries.all() }), + invalidateQueries(queryClient, { queryKey: todosQueries.all() }), }) const clearMutation = useMutation({ ...todosMutations.deleteAll(), onSuccess: () => - queryClient.invalidateQueries({ queryKey: todosQueries.all() }), + invalidateQueries(queryClient, { queryKey: todosQueries.all() }), }) - if (status === 'pending') return

Loading...

- if (status === 'error') return Error: {error.message} + if (queryResult.status === 'pending') return

Loading...

+ if (queryResult.status === 'error') + return Error: {queryResult.error.message} return (
@@ -51,8 +62,8 @@ export default function App() { marginLeft: '.5rem', width: 10, height: 10, - background: isFetching ? 'green' : 'transparent', - transition: !isFetching ? 'all .3s ease' : 'none', + background: isFetching(queryResult) ? 'green' : 'transparent', + transition: !isFetching(queryResult) ? 'all .3s ease' : 'none', borderRadius: '100%', transform: 'scale(2)', }} @@ -76,7 +87,7 @@ export default function App() { />
    - {data.map((item) => ( + {queryResult.data.map((item) => (
  • {item}
  • ))}
diff --git a/examples/preact/basic-graphql-request/src/index.tsx b/examples/preact/basic-graphql-request/src/index.tsx index 1ac69a2282e..a4df3565dc3 100644 --- a/examples/preact/basic-graphql-request/src/index.tsx +++ b/examples/preact/basic-graphql-request/src/index.tsx @@ -1,6 +1,8 @@ import { QueryClient, QueryClientProvider, + getQueryData, + isFetching, useQuery, useQueryClient, } from '@tanstack/preact-query' @@ -38,20 +40,20 @@ function App() { function Posts({ setPostId }: { setPostId: (postId: string | null) => void }) { const queryClient = useQueryClient() - const { status, data, error, isFetching } = useQuery(postsQueries.list()) + const queryResult = useQuery(postsQueries.list()) return (

Posts

- {status === 'pending' ? ( + {queryResult.status === 'pending' ? ( 'Loading...' - ) : status === 'error' ? ( - Error: {error.message} + ) : queryResult.status === 'error' ? ( + Error: {queryResult.error.message} ) : ( <> -
{isFetching ? 'Background Updating...' : ' '}
+
+ {isFetching(queryResult) ? 'Background Updating...' : ' '} +
)}
@@ -89,9 +94,7 @@ function Post({ postId: string setPostId: (postId: string | null) => void }) { - const { status, data, error, isFetching } = useQuery( - postsQueries.detail(postId), - ) + const detailQuery = useQuery(postsQueries.detail(postId)) return ( - {status === 'pending' ? ( + {detailQuery.status === 'pending' ? ( 'Loading...' - ) : status === 'error' ? ( - Error: {error.message} + ) : detailQuery.status === 'error' ? ( + Error: {detailQuery.error.message} ) : ( <> -

{data.title}

+

{detailQuery.data.title}

-

{data.body}

+

{detailQuery.data.body}

-
{isFetching ? 'Background Updating...' : ' '}
+
{isFetching(detailQuery) ? 'Background Updating...' : ' '}
)}
diff --git a/examples/preact/basic/src/index.tsx b/examples/preact/basic/src/index.tsx index ceaa985b6e2..0356432b664 100644 --- a/examples/preact/basic/src/index.tsx +++ b/examples/preact/basic/src/index.tsx @@ -1,4 +1,10 @@ -import { QueryClient, useQuery, useQueryClient } from '@tanstack/preact-query' +import { + QueryClient, + getQueryData, + isFetching, + useQuery, + useQueryClient, +} from '@tanstack/preact-query' import { PreactQueryDevtools } from '@tanstack/preact-query-devtools' import { PersistQueryClientProvider } from '@tanstack/preact-query-persist-client' import { createAsyncStoragePersister } from '@tanstack/query-async-storage-persister' @@ -20,20 +26,20 @@ const persister = createAsyncStoragePersister({ function Posts({ setPostId }: { setPostId: (postId: number) => void }) { const queryClient = useQueryClient() - const { status, data, error, isFetching } = useQuery(postsQueries.list()) + const queryResult = useQuery(postsQueries.list()) return (

Posts

- {status === 'pending' ? ( + {queryResult.status === 'pending' ? ( 'Loading...' - ) : status === 'error' ? ( - Error: {error.message} + ) : queryResult.status === 'error' ? ( + Error: {queryResult.error.message} ) : ( <> -
{isFetching ? 'Background Updating...' : ' '}
+
+ {isFetching(queryResult) ? 'Background Updating...' : ' '} +
)}
@@ -71,9 +80,7 @@ function Post({ postId: number setPostId: (postId: number) => void }) { - const { status, data, error, isFetching } = useQuery( - postsQueries.detail(postId), - ) + const detailQuery = useQuery(postsQueries.detail(postId)) return ( - {status === 'pending' ? ( + {detailQuery.status === 'pending' ? ( 'Loading...' - ) : status === 'error' ? ( - Error: {error.message} + ) : detailQuery.status === 'error' ? ( + Error: {detailQuery.error.message} ) : ( <> -

{data.title}

+

{detailQuery.data.title}

-

{data.body}

+

{detailQuery.data.body}

-
{isFetching ? 'Background Updating...' : ' '}
+
{isFetching(detailQuery) ? 'Background Updating...' : ' '}
)}
diff --git a/examples/preact/chat/src/index.tsx b/examples/preact/chat/src/index.tsx index 572dbfed6ed..645e5af9d5a 100644 --- a/examples/preact/chat/src/index.tsx +++ b/examples/preact/chat/src/index.tsx @@ -1,6 +1,7 @@ import { QueryClient, QueryClientProvider, + isFetching, useQuery, } from '@tanstack/preact-query' import { PreactQueryDevtools } from '@tanstack/preact-query-devtools' @@ -22,20 +23,20 @@ export default function App() { } function ChatMessage({ id, question }: { id: string; question: string }) { - const { - error, - data = [], - isFetching, - } = useQuery(messagesQueries.detail(id, question)) + const queryResult = useQuery(messagesQueries.detail(id, question)) - if (error) return `An error has occurred: ${error.message}` + if (queryResult.error) + return `An error has occurred: ${queryResult.error.message}` return (
) diff --git a/examples/preact/default-query-function/src/index.tsx b/examples/preact/default-query-function/src/index.tsx index fd3a114dad0..be3d8c232a5 100644 --- a/examples/preact/default-query-function/src/index.tsx +++ b/examples/preact/default-query-function/src/index.tsx @@ -2,6 +2,9 @@ import { QueryClient, QueryClientProvider, defaultQueryFn, + getQueryData, + isFetching, + queryOptions, useQuery, useQueryClient, } from '@tanstack/preact-query' @@ -62,23 +65,25 @@ function App() { function Posts({ setPostId }: { setPostId: (postId: number) => void }) { const queryClient = useQueryClient() - const { status, data, error, isFetching } = useQuery>({ - queryKey: ['/posts'], - queryFn: defaultQueryFn, - }) + const queryResult = useQuery( + queryOptions>({ + queryKey: ['/posts'], + queryFn: defaultQueryFn, + }), + ) return (

Posts

- {status === 'pending' ? ( + {queryResult.status === 'pending' ? ( 'Loading...' - ) : status === 'error' ? ( - Error: {error.message} + ) : queryResult.status === 'error' ? ( + Error: {queryResult.error.message} ) : ( <> -
{isFetching ? 'Background Updating...' : ' '}
+
+ {isFetching(queryResult) ? 'Background Updating...' : ' '} +
)}
@@ -114,11 +121,13 @@ function Post({ postId: number setPostId: (postId: number) => void }) { - const { status, data, error, isFetching } = useQuery({ - queryKey: [`/posts/${postId}`], - queryFn: defaultQueryFn, - enabled: !!postId, - }) + const detailQuery = useQuery( + queryOptions({ + queryKey: [`/posts/${postId}`], + queryFn: defaultQueryFn, + enabled: !!postId, + }), + ) return ( - {!postId || status === 'pending' ? ( + {!postId || detailQuery.status === 'pending' ? ( 'Loading...' - ) : status === 'error' ? ( - Error: {error.message} + ) : detailQuery.status === 'error' ? ( + Error: {detailQuery.error.message} ) : ( <> -

{data.title}

+

{detailQuery.data.title}

-

{data.body}

+

{detailQuery.data.body}

-
{isFetching ? 'Background Updating...' : ' '}
+
{isFetching(detailQuery) ? 'Background Updating...' : ' '}
)}
diff --git a/examples/preact/devtools-panel/src/index.tsx b/examples/preact/devtools-panel/src/index.tsx index f01dc4e080e..af661724d0e 100644 --- a/examples/preact/devtools-panel/src/index.tsx +++ b/examples/preact/devtools-panel/src/index.tsx @@ -1,6 +1,8 @@ import { QueryClient, QueryClientProvider, + isFetching, + isPending, useQuery, } from '@tanstack/preact-query' import { PreactQueryDevtoolsPanel } from '@tanstack/preact-query-devtools' @@ -25,11 +27,12 @@ export default function App() { } function Example() { - const { isPending, error, data, isFetching } = useQuery(reposQueries.detail()) + const queryResult = useQuery(reposQueries.detail()) - if (isPending) return 'Loading...' + if (isPending(queryResult)) return 'Loading...' - if (error) return `An error has occurred: ${error.message}` + if (queryResult.error) + return `An error has occurred: ${queryResult.error.message}` return (
-

{data.full_name}

-

{data.description}

- 👀 {data.subscribers_count}{' '} - ✨ {data.stargazers_count}{' '} - 🍴 {data.forks_count} -
{isFetching ? 'Updating...' : ''}
+

{queryResult.data.full_name}

+

{queryResult.data.description}

+ 👀 {queryResult.data.subscribers_count}{' '} + ✨ {queryResult.data.stargazers_count}{' '} + 🍴 {queryResult.data.forks_count} +
{isFetching(queryResult) ? 'Updating...' : ''}
) } diff --git a/examples/preact/infinite-query-with-max-pages/src/App.tsx b/examples/preact/infinite-query-with-max-pages/src/App.tsx index e23a369a542..9eba828f9a4 100644 --- a/examples/preact/infinite-query-with-max-pages/src/App.tsx +++ b/examples/preact/infinite-query-with-max-pages/src/App.tsx @@ -1,46 +1,43 @@ -import { useInfiniteQuery } from '@tanstack/preact-query' +import { + isFetching, + isFetchingNextPage, + isFetchingPreviousPage, + useQuery, +} from '@tanstack/preact-query' import { PreactQueryDevtools } from '@tanstack/preact-query-devtools' import { Fragment } from 'preact' import { projectsQueries } from './services/projects/queries' export default function App() { - const { - status, - data, - error, - isFetching, - isFetchingNextPage, - isFetchingPreviousPage, - fetchNextPage, - fetchPreviousPage, - hasNextPage, - hasPreviousPage, - } = useInfiniteQuery(projectsQueries.infinite()) + const queryResult = useQuery(projectsQueries.infinite()) return (

Infinite Query with max pages

4 projects per page

3 pages max

- {status === 'pending' ? ( + {queryResult.status === 'pending' ? (

Loading...

- ) : status === 'error' ? ( - Error: {error.message} + ) : queryResult.status === 'error' ? ( + Error: {queryResult.error.message} ) : ( <>
- {data.pages.map((page) => ( + {queryResult.data.pages.map((page) => ( {page.data.map((project) => (

- {isFetching && !isFetchingNextPage + {isFetching(queryResult) && !isFetchingNextPage(queryResult) ? 'Background Updating...' : null}
diff --git a/examples/preact/load-more-infinite-scroll-preact-iso/src/Example.tsx b/examples/preact/load-more-infinite-scroll-preact-iso/src/Example.tsx index c9d8f0ddd4b..1e2fad066f8 100644 --- a/examples/preact/load-more-infinite-scroll-preact-iso/src/Example.tsx +++ b/examples/preact/load-more-infinite-scroll-preact-iso/src/Example.tsx @@ -1,4 +1,9 @@ -import { useInfiniteQuery } from '@tanstack/preact-query' +import { + isFetching, + isFetchingNextPage, + isFetchingPreviousPage, + useQuery, +} from '@tanstack/preact-query' import { PreactQueryDevtools } from '@tanstack/preact-query-devtools' import { Fragment } from 'preact' import { useEffect, useRef, useState } from 'preact/hooks' @@ -8,18 +13,7 @@ export default function Example() { const ref = useRef(null) const [inView, setInView] = useState(false) - const { - status, - data, - error, - isFetching, - isFetchingNextPage, - isFetchingPreviousPage, - fetchNextPage, - fetchPreviousPage, - hasNextPage, - hasPreviousPage, - } = useInfiniteQuery(projectsQueries.infinite()) + const queryResult = useQuery(projectsQueries.infinite()) useEffect(() => { if (!ref.current) return @@ -30,36 +24,44 @@ export default function Example() { observer.observe(ref.current) return () => observer.disconnect() - }, [status]) + }, [queryResult.status]) useEffect(() => { - if (inView && hasNextPage && !isFetchingNextPage) { - fetchNextPage() + if (inView && queryResult.hasNextPage && !isFetchingNextPage(queryResult)) { + queryResult.fetchNextPage() } - }, [inView, hasNextPage, isFetchingNextPage, fetchNextPage]) + }, [ + inView, + queryResult.hasNextPage, + isFetchingNextPage(queryResult), + queryResult.fetchNextPage, + ]) return (

Infinite Loading

- {status === 'pending' ? ( + {queryResult.status === 'pending' ? (

Loading...

- ) : status === 'error' ? ( - Error: {error.message} + ) : queryResult.status === 'error' ? ( + Error: {queryResult.error.message} ) : ( <>
- {data.pages.map((page) => ( + {queryResult.data.pages.map((page) => ( {page.data.map((project) => (

- {isFetching && !isFetchingNextPage + {isFetching(queryResult) && !isFetchingNextPage(queryResult) ? 'Background Updating...' : null}
diff --git a/examples/preact/offline-preact-iso/src/App.tsx b/examples/preact/offline-preact-iso/src/App.tsx index 07aa701a405..c815cd2811f 100644 --- a/examples/preact/offline-preact-iso/src/App.tsx +++ b/examples/preact/offline-preact-iso/src/App.tsx @@ -1,8 +1,19 @@ import { MutationCache, QueryClient, + cancelQueries, + getQueryData, + invalidateQueries, + isError, + isFetching, + isLoading, + isPaused, noop, onlineManager, + query, + resumePausedMutations, + setMutationDefaults, + setQueryData, useIsRestoring, useMutation, useQuery, @@ -36,7 +47,7 @@ const queryClient = new QueryClient({ }) // we need a default mutation function so that paused mutations can resume after a page reload -queryClient.setMutationDefaults(moviesQueries.all(), { +setMutationDefaults(queryClient, moviesQueries.all(), { ...moviesMutations.update(), onSuccess: (data) => { toaster.success({ title: data.message }) @@ -50,8 +61,8 @@ export default function App() { persistOptions={{ persister }} onSuccess={() => { // resume mutations after initial restore from localStorage was successful - queryClient.resumePausedMutations().then(() => { - queryClient.invalidateQueries() + resumePausedMutations(queryClient).then(() => { + invalidateQueries(queryClient) }) }} > @@ -71,7 +82,7 @@ function List() { const isRestoring = useIsRestoring() const moviesQuery = useQuery(moviesQueries.list()) - if (moviesQuery.isLoading) { + if (isLoading(moviesQuery)) { return 'Loading...' } @@ -93,9 +104,9 @@ function List() { // do not prefetch if we are offline or hydrating because it returns a promise that is pending until we go online again // we just let the Detail component handle it if (onlineManager.isOnline() && !isRestoring) { - queryClient - .query(moviesQueries.detail(movie.id)) - .catch(noop) + query(queryClient, moviesQueries.detail(movie.id)).catch( + noop, + ) } }} > @@ -107,12 +118,12 @@ function List() {
Updated at: {new Date(moviesQuery.data.ts).toLocaleTimeString()}
-
{moviesQuery.isFetching && 'fetching...'}
+
{isFetching(moviesQuery) && 'fetching...'}
) } - if (moviesQuery.isError) { + if (isError(moviesQuery)) { return (

Couldn't load movies!

@@ -135,16 +146,17 @@ function Detail() { ...moviesMutations.update(), mutationKey: moviesQueries.detail(movieId).queryKey, onMutate: async (variables) => { - await queryClient.cancelQueries({ + await cancelQueries(queryClient, { queryKey: moviesQueries.detail(movieId).queryKey, }) const { queryKey } = moviesQueries.detail(movieId) - const previousData = queryClient.getQueryData(queryKey) + const previousData = getQueryData(queryClient, queryKey) // remove local state so that server state is taken instead setCommentDraft(undefined) - queryClient.setQueryData( + setQueryData( + queryClient, queryKey, (old) => old && { @@ -159,13 +171,14 @@ function Detail() { return { previousData } }, onError: (_, __, onMutateResult) => { - queryClient.setQueryData( + setQueryData( + queryClient, moviesQueries.detail(movieId).queryKey, onMutateResult?.previousData, ) }, onSettled: () => { - queryClient.invalidateQueries({ + invalidateQueries(queryClient, { queryKey: moviesQueries.detail(movieId).queryKey, }) }, @@ -173,7 +186,7 @@ function Detail() { const comment = commentDraft ?? movieQuery.data?.movie.comment - if (movieQuery.isLoading) { + if (isLoading(movieQuery)) { return 'Loading...' } @@ -218,7 +231,7 @@ function Detail() {
Updated at: {new Date(movieQuery.data.ts).toLocaleTimeString()}
-
{movieQuery.isFetching && 'fetching...'}
+
{isFetching(movieQuery) && 'fetching...'}
{updateMovie.isPaused ? 'mutation paused - offline' @@ -228,7 +241,7 @@ function Detail() { ) } - if (movieQuery.isError) { + if (isError(movieQuery)) { return (
Back @@ -238,7 +251,7 @@ function Detail() { ) } - if (movieQuery.isPaused) { + if (isPaused(movieQuery)) { return "We're offline and have no data to show :(" } diff --git a/examples/preact/offline-preact-iso/src/services/movies/queries.ts b/examples/preact/offline-preact-iso/src/services/movies/queries.ts index 026c5ead1e9..30a7b823776 100644 --- a/examples/preact/offline-preact-iso/src/services/movies/queries.ts +++ b/examples/preact/offline-preact-iso/src/services/movies/queries.ts @@ -1,4 +1,8 @@ -import { mutationOptions, queryOptions } from '@tanstack/preact-query' +import { + cancelQueries, + mutationOptions, + queryOptions, +} from '@tanstack/preact-query' import { moviesAPI } from './api' export const moviesQueries = { @@ -23,7 +27,7 @@ export const moviesMutations = { context, ) => { // to avoid clashes with our optimistic update when an offline mutation continues - await context.client.cancelQueries({ + await cancelQueries(context.client, { queryKey: moviesQueries.detail(id).queryKey, }) return moviesAPI.updateMovie(id, comment) diff --git a/examples/preact/optimistic-updates/src/components/TodoListCache.tsx b/examples/preact/optimistic-updates/src/components/TodoListCache.tsx index 177f0011452..727a03e54b4 100644 --- a/examples/preact/optimistic-updates/src/components/TodoListCache.tsx +++ b/examples/preact/optimistic-updates/src/components/TodoListCache.tsx @@ -1,7 +1,12 @@ import { + cancelQueries, + getQueryData, + invalidateQueries, + setQueryData, + suspenseQueryOptions, useMutation, + useQuery, useQueryClient, - useSuspenseQuery, } from '@tanstack/preact-query' import { useState } from 'preact/hooks' import { todosMutations, todosQueries } from '../services/todos/queries' @@ -17,17 +22,18 @@ export default function TodoListCache() { const [inputValue, setInputValue] = useState('') const [lastError, setLastError] = useState(null) - const { data: todos } = useSuspenseQuery(todosQueries.list()) + const { data: todos } = useQuery(suspenseQueryOptions(todosQueries.list())) const addTodoMutation = useMutation({ ...todosMutations.create(), onMutate: async (text) => { setLastError(null) - await queryClient.cancelQueries({ + await cancelQueries(queryClient, { queryKey: todosQueries.list().queryKey, }) - const previousTodos = queryClient.getQueryData( + const previousTodos = getQueryData( + queryClient, todosQueries.list().queryKey, ) @@ -38,7 +44,7 @@ export default function TodoListCache() { createdAt: Date.now(), } - queryClient.setQueryData(todosQueries.list().queryKey, (old = []) => [ + setQueryData(queryClient, todosQueries.list().queryKey, (old = []) => [ ...old, optimisticTodo, ]) @@ -48,18 +54,21 @@ export default function TodoListCache() { onError: (_err, _text, context) => { setLastError(_err.message) if (context?.previousTodos !== undefined) { - queryClient.setQueryData( + setQueryData( + queryClient, todosQueries.list().queryKey, context.previousTodos, ) } else if (context?.optimisticId) { - queryClient.setQueryData(todosQueries.list().queryKey, (old = []) => + setQueryData(queryClient, todosQueries.list().queryKey, (old = []) => old.filter((todo) => todo.id !== context.optimisticId), ) } }, onSettled: () => - queryClient.invalidateQueries({ queryKey: todosQueries.list().queryKey }), + invalidateQueries(queryClient, { + queryKey: todosQueries.list().queryKey, + }), }) function handleSubmit(e: SubmitEvent) { diff --git a/examples/preact/optimistic-updates/src/components/TodoListUI.tsx b/examples/preact/optimistic-updates/src/components/TodoListUI.tsx index f72e19eee21..81a65af6e05 100644 --- a/examples/preact/optimistic-updates/src/components/TodoListUI.tsx +++ b/examples/preact/optimistic-updates/src/components/TodoListUI.tsx @@ -1,7 +1,9 @@ import { + invalidateQueries, + suspenseQueryOptions, useMutation, + useQuery, useQueryClient, - useSuspenseQuery, } from '@tanstack/preact-query' import { useState } from 'preact/hooks' import { todosMutations, todosQueries } from '../services/todos/queries' @@ -10,12 +12,14 @@ export default function TodoListUI() { const queryClient = useQueryClient() const [inputValue, setInputValue] = useState('') - const { data: todos } = useSuspenseQuery(todosQueries.list()) + const { data: todos } = useQuery(suspenseQueryOptions(todosQueries.list())) const addTodoMutation = useMutation({ ...todosMutations.create(), onSettled: () => - queryClient.invalidateQueries({ queryKey: todosQueries.list().queryKey }), + invalidateQueries(queryClient, { + queryKey: todosQueries.list().queryKey, + }), }) function handleSubmit(e: SubmitEvent) { diff --git a/examples/preact/pagination/src/App.tsx b/examples/preact/pagination/src/App.tsx index 14525209f28..a5d5e4ea394 100644 --- a/examples/preact/pagination/src/App.tsx +++ b/examples/preact/pagination/src/App.tsx @@ -1,6 +1,10 @@ import { + isFetching, keepPreviousData, noop, + placeholderData, + query, + queryOptions, useQuery, useQueryClient, } from '@tanstack/preact-query' @@ -12,17 +16,19 @@ export default function App() { const queryClient = useQueryClient() const [page, setPage] = useState(0) - const { status, data, error, isFetching, isPlaceholderData } = useQuery({ - ...projectsQueries.list(page), - placeholderData: keepPreviousData, - }) + const queryResult = useQuery( + queryOptions({ + ...projectsQueries.list(page), + placeholderData: placeholderData(keepPreviousData), + }), + ) // Prefetch the next page! useEffect(() => { - if (!isPlaceholderData && data?.hasMore) { - queryClient.query(projectsQueries.list(page + 1)).catch(noop) + if (!queryResult.isPlaceholderData && queryResult.data?.hasMore) { + query(queryClient, projectsQueries.list(page + 1)).catch(noop) } - }, [data, isPlaceholderData, page, queryClient]) + }, [queryResult.data, queryResult.isPlaceholderData, page, queryClient]) return (
@@ -34,15 +40,15 @@ export default function App() { instantaneously while they are also refetched invisibly in the background.

- {status === 'pending' ? ( + {queryResult.status === 'pending' ? (
Loading...
- ) : status === 'error' ? ( -
Error: {error.message}
+ ) : queryResult.status === 'error' ? ( +
Error: {queryResult.error.message}
) : ( // `data` will either resolve to the latest page's data // or if fetching a new page, the last successful page's data
- {data.projects.map((project) => ( + {queryResult.data.projects.map((project) => (

{project.name}

))}
@@ -56,9 +62,9 @@ export default function App() { {' '} @@ -66,7 +72,7 @@ export default function App() { // Since the last page's data potentially sticks around between page requests, // we can use `isFetching` to show a background loading // indicator since our `status === 'pending'` state won't be triggered - isFetching ? Loading... : null + isFetching(queryResult) ? Loading... : null }{' '}
diff --git a/examples/preact/playground/src/index.tsx b/examples/preact/playground/src/index.tsx index e35affa6e64..271d0dc018b 100644 --- a/examples/preact/playground/src/index.tsx +++ b/examples/preact/playground/src/index.tsx @@ -1,6 +1,10 @@ import { QueryClient, QueryClientProvider, + invalidateQueries, + isFetching, + setDefaultOptions, + setQueryData, useMutation, useQuery, useQueryClient, @@ -53,7 +57,7 @@ function Root() { }, [localErrorRate, localFetchTimeMax, localFetchTimeMin]) useEffect(() => { - queryClient.setDefaultOptions({ + setDefaultOptions(queryClient, { queries: { staleTime, gcTime, @@ -140,7 +144,7 @@ function App() { return (
-
@@ -184,9 +188,7 @@ function Todos({ }) { const [filter, setFilter] = useState(initialFilter) - const { status, data, isFetching, error, failureCount, refetch } = useQuery( - todosQueries.list(filter), - ) + const queryResult = useQuery(todosQueries.list(filter)) return (
@@ -199,18 +201,18 @@ function Todos({ />
- {status === 'pending' ? ( - Loading... (Attempt: {failureCount + 1}) - ) : status === 'error' ? ( + {queryResult.status === 'pending' ? ( + Loading... (Attempt: {queryResult.failureCount + 1}) + ) : queryResult.status === 'error' ? ( - Error: {error.message} + Error: {queryResult.error.message}
- +
) : ( <>
    - {data.map((todo) => ( + {queryResult.data.map((todo) => (
  • {todo.name}{' '} @@ -218,9 +220,10 @@ function Todos({ ))}
- {isFetching ? ( + {isFetching(queryResult) ? ( - Background Refreshing... (Attempt: {failureCount + 1}) + Background Refreshing... (Attempt:{' '} + {queryResult.failureCount + 1}) ) : (   @@ -241,9 +244,7 @@ function EditTodo({ }) { const queryClient = useQueryClient() - const { status, data, isFetching, failureCount, refetch } = useQuery( - todosQueries.detail(editingIndex), - ) + const detailQuery = useQuery(todosQueries.detail(editingIndex)) const [draft, setDraft] = useState>>({}) @@ -251,38 +252,42 @@ function EditTodo({ ...todosMutations.update(), onSuccess: (todo) => { // Update `todos` and the individual todo queries when this mutation succeeds - queryClient.invalidateQueries({ queryKey: todosQueries.lists() }) - queryClient.setQueryData(todosQueries.detail(editingIndex).queryKey, todo) + invalidateQueries(queryClient, { queryKey: todosQueries.lists() }) + setQueryData( + queryClient, + todosQueries.detail(editingIndex).queryKey, + todo, + ) setDraft({}) }, }) const disableEditSave = - status === 'pending' || saveMutation.status === 'pending' + detailQuery.status === 'pending' || saveMutation.status === 'pending' return (
- {data ? ( + {detailQuery.data ? ( <> Editing - Todo "{data.name}" (# + Todo "{detailQuery.data.name}" (# {editingIndex}) ) : null}
- {status === 'pending' ? ( - Loading... (Attempt: {failureCount + 1}) - ) : status === 'error' ? ( + {detailQuery.status === 'pending' ? ( + Loading... (Attempt: {detailQuery.failureCount + 1}) + ) : detailQuery.status === 'error' ? ( - Error! + Error! ) : ( <>