From 3d3c3505216a725d083c793b1bfc6ff61efa4f02 Mon Sep 17 00:00:00 2001 From: Jonghyeon Ko Date: Sat, 28 Nov 2026 23:03:44 +0900 Subject: [PATCH 01/11] feat: make the v6 query core and framework adapters treeshakable --- .changeset/treeshakable-query.md | 19 + .github/workflows/query-bundle-size.yml | 113 + .size-limit.json | 2 +- docs/config.json | 4 + docs/framework/angular/guides/polling.md | 24 +- .../framework/angular/guides/query-options.md | 10 +- docs/framework/preact/quick-start.md | 6 +- docs/framework/react/comparison.md | 2 +- docs/framework/react/graphql.md | 24 +- docs/framework/react/guides/advanced-ssr.md | 124 +- .../guides/background-fetching-indicators.md | 29 +- docs/framework/react/guides/caching.md | 14 +- .../react/guides/default-query-function.md | 32 +- .../react/guides/dependent-queries.md | 39 +- .../react/guides/disabling-queries.md | 58 +- docs/framework/react/guides/filters.md | 14 +- .../react/guides/important-defaults.md | 6 +- .../react/guides/infinite-queries.md | 152 +- .../react/guides/initial-query-data.md | 144 +- .../guides/invalidations-from-mutations.md | 12 +- .../framework/react/guides/migrating-to-v6.md | 118 + docs/framework/react/guides/mutations.md | 24 +- docs/framework/react/guides/network-mode.md | 2 +- .../react/guides/optimistic-updates.md | 25 +- .../react/guides/paginated-queries.md | 47 +- .../react/guides/parallel-queries.md | 10 +- .../react/guides/placeholder-query-data.md | 68 +- docs/framework/react/guides/polling.md | 48 +- docs/framework/react/guides/prefetching.md | 138 +- docs/framework/react/guides/queries.md | 28 +- .../react/guides/query-cancellation.md | 188 +- .../framework/react/guides/query-functions.md | 95 +- .../react/guides/query-invalidation.md | 115 +- docs/framework/react/guides/query-keys.md | 32 +- docs/framework/react/guides/query-options.md | 19 +- docs/framework/react/guides/query-retries.md | 48 +- .../react/guides/render-optimizations.md | 38 +- .../react/guides/request-waterfalls.md | 100 +- docs/framework/react/guides/ssr.md | 118 +- docs/framework/react/guides/suspense.md | 30 +- docs/framework/react/guides/testing.md | 20 +- .../guides/updates-from-mutation-responses.md | 21 +- .../react/guides/window-focus-refetching.md | 12 +- docs/framework/react/overview.md | 12 +- .../react/plugins/createPersister.md | 6 +- .../react/plugins/persistQueryClient.md | 2 +- docs/framework/react/quick-start.md | 6 +- docs/framework/react/react-native.md | 10 +- docs/framework/react/typescript.md | 105 +- docs/framework/solid/guides/polling.md | 24 +- docs/framework/solid/guides/query-options.md | 10 +- .../components/auto-refetching.component.ts | 8 +- .../optimistic-updates.component.ts | 18 +- .../src/app/components/example.component.ts | 10 +- .../src/app/components/example.component.ts | 8 +- examples/lit/algolia/src/search-results.ts | 4 +- examples/lit/auto-refetching/src/main.ts | 8 +- .../basic-graphql-request/src/post-list.ts | 9 +- examples/lit/basic/src/basic-query.ts | 6 +- examples/lit/basic/src/lifecycle-contract.ts | 3 +- examples/lit/basic/src/main.ts | 16 +- examples/lit/basic/src/mutation.ts | 4 +- .../default-query-function/src/post-list.ts | 3 +- .../lit/offline-lit-labs-router/src/main.ts | 18 +- .../src/movie-detail-view.ts | 16 +- .../src/queryClient.ts | 8 +- .../src/services/movies/queries.ts | 8 +- .../optimistic-updates/src/todo-list-cache.ts | 20 +- .../optimistic-updates/src/todo-list-ui.ts | 3 +- examples/lit/pagination/src/main.ts | 38 +- examples/lit/playground/src/add-todo.ts | 7 +- examples/lit/playground/src/edit-todo.ts | 10 +- examples/lit/playground/src/main.ts | 11 +- .../src/character-item.ts | 11 +- .../src/home-view.ts | 10 +- examples/lit/ssr/server/index.mjs | 3 +- examples/lit/ssr/src/app.ts | 17 +- examples/lit/ssr/src/main.ts | 11 +- examples/preact/algolia/src/SearchResults.tsx | 22 +- examples/preact/auto-refetching/src/App.tsx | 25 +- .../basic-graphql-request/src/index.tsx | 11 +- examples/preact/basic/src/index.tsx | 17 +- examples/preact/chat/src/index.tsx | 3 +- .../default-query-function/src/index.tsx | 26 +- examples/preact/devtools-panel/src/index.tsx | 5 +- .../infinite-query-with-max-pages/src/App.tsx | 4 +- .../src/Example.tsx | 4 +- .../preact/offline-preact-iso/src/App.tsx | 54 +- .../src/services/movies/queries.ts | 8 +- .../src/components/TodoListCache.tsx | 25 +- .../src/components/TodoListUI.tsx | 10 +- examples/preact/pagination/src/App.tsx | 15 +- examples/preact/playground/src/index.tsx | 22 +- .../prefetching-preact-iso/src/Character.tsx | 4 +- .../prefetching-preact-iso/src/Home.tsx | 44 +- .../rick-morty-preact-iso/src/Character.tsx | 14 +- .../rick-morty-preact-iso/src/Characters.tsx | 4 +- .../rick-morty-preact-iso/src/Episode.tsx | 10 +- .../rick-morty-preact-iso/src/Episodes.tsx | 4 +- examples/preact/shadow-dom/src/DogList.tsx | 4 +- examples/preact/simple/src/index.tsx | 23 +- examples/preact/ssr-streaming/src/App.tsx | 6 +- .../preact/ssr-streaming/src/entry-server.tsx | 12 +- examples/preact/ssr/src/App.tsx | 25 +- examples/preact/ssr/src/entry-server.tsx | 5 +- .../star-wars-preact-iso/src/Character.tsx | 12 +- .../star-wars-preact-iso/src/Characters.tsx | 4 +- .../preact/star-wars-preact-iso/src/Film.tsx | 8 +- .../preact/star-wars-preact-iso/src/Films.tsx | 4 +- .../suspense/src/components/Project.tsx | 6 +- .../suspense/src/components/Projects.tsx | 19 +- examples/preact/suspense/src/index.tsx | 3 +- examples/react/algolia/README.md | 2 +- examples/react/algolia/src/SearchResults.tsx | 37 +- .../algolia/src/services/products/queries.ts | 5 +- .../README.md | 4 +- .../src/pages/index.tsx | 32 +- .../react/basic-graphql-request/README.md | 2 +- .../react/basic-graphql-request/src/index.tsx | 19 +- examples/react/basic/README.md | 2 +- examples/react/basic/src/index.tsx | 25 +- examples/react/chat/src/index.tsx | 11 +- .../react/contacts-react-router/README.md | 6 +- .../src/routes/contact.tsx | 8 +- .../src/routes/destroy.tsx | 3 +- .../contacts-react-router/src/routes/edit.tsx | 6 +- .../contacts-react-router/src/routes/new.tsx | 3 +- .../contacts-react-router/src/routes/root.tsx | 9 +- .../src/services/contacts/queries.ts | 6 +- .../react/contacts-tanstack-router/README.md | 6 +- .../src/routes/__root.tsx | 6 +- .../src/routes/contacts.$contactId.edit.tsx | 7 +- .../src/routes/contacts.$contactId.index.tsx | 9 +- .../src/routes/contacts.$contactId.route.tsx | 3 +- .../src/routes/contacts.new.tsx | 8 +- .../src/services/contacts/queries.ts | 6 +- .../react/default-query-function/README.md | 8 +- .../default-query-function/src/index.tsx | 35 +- examples/react/devtools-panel/src/index.tsx | 22 +- .../src/prefer-query-options-demo.tsx | 30 +- .../hydration-nextjs-pages-router/README.md | 2 +- .../src/components/PostList.tsx | 17 +- .../src/pages/index.tsx | 4 +- .../README.md | 2 +- .../src/pages/index.tsx | 28 +- .../README.md | 2 +- .../src/pages/index.tsx | 32 +- examples/react/offline-react-router/README.md | 6 +- .../react/offline-react-router/src/App.tsx | 14 +- .../src/routes/detail.tsx | 33 +- .../offline-react-router/src/routes/list.tsx | 8 +- .../src/services/movies/queries.ts | 8 +- .../react/offline-tanstack-router/README.md | 6 +- .../react/offline-tanstack-router/src/App.tsx | 9 +- .../src/routes/$movieId.tsx | 33 +- .../src/routes/index.tsx | 8 +- .../src/services/movies/queries.ts | 8 +- .../README.md | 10 +- .../app/page.tsx | 17 +- .../components/TodoListCache.tsx | 24 +- .../components/TodoListUI.tsx | 9 +- .../services/todos/queries.ts | 4 +- .../pagination-nextjs-pages-router/README.md | 2 +- .../src/pages/index.tsx | 20 +- examples/react/playground/README.md | 4 +- examples/react/playground/src/index.tsx | 34 +- .../prefetching-nextjs-app-router/README.md | 6 +- .../app/page.tsx | 9 +- .../app/pokemon-info.tsx | 4 +- .../services/pokemons/queries.ts | 4 +- .../prefetching-nextjs-pages-router/README.md | 2 +- .../src/pages/character/[id].tsx | 8 +- .../src/pages/index.tsx | 38 +- examples/react/react-native/README.md | 4 +- .../src/hooks/useRefreshOnFocus.ts | 4 +- .../src/screens/MovieDetailsScreen.tsx | 55 +- .../src/screens/MoviesListScreen.tsx | 14 +- examples/react/simple/src/index.tsx | 43 +- .../README.md | 4 +- .../src/app/page.tsx | 4 +- .../src/services/wait/queries.ts | 4 +- examples/react/suspense/README.md | 6 +- .../react/suspense/src/components/Project.tsx | 10 +- .../suspense/src/components/Projects.tsx | 21 +- examples/react/suspense/src/index.tsx | 3 +- .../suspense/src/services/projects/queries.ts | 6 +- examples/solid/algolia/src/SearchResults.tsx | 15 +- .../src/routes/index.tsx | 19 +- .../solid/basic-graphql-request/src/index.tsx | 11 +- examples/solid/basic/src/index.tsx | 11 +- examples/solid/chat/src/index.tsx | 6 +- .../src/routes/contact.tsx | 6 +- .../src/routes/destroy.tsx | 3 +- .../contacts-solid-router/src/routes/edit.tsx | 4 +- .../contacts-solid-router/src/routes/new.tsx | 3 +- .../contacts-solid-router/src/routes/root.tsx | 9 +- .../src/routes/__root.tsx | 4 +- .../src/routes/contacts.$contactId.edit.tsx | 9 +- .../src/routes/contacts.$contactId.index.tsx | 11 +- .../src/routes/contacts.$contactId.route.tsx | 3 +- .../src/routes/contacts.new.tsx | 8 +- .../default-query-function/src/index.tsx | 10 +- examples/solid/devtools-panel/src/index.tsx | 12 +- .../solid/offline-solid-router/src/App.tsx | 14 +- .../src/routes/detail.tsx | 33 +- .../offline-solid-router/src/routes/list.tsx | 8 +- .../src/services/movies/queries.ts | 8 +- .../solid/offline-tanstack-router/src/App.tsx | 9 +- .../src/routes/$movieId.tsx | 33 +- .../src/routes/index.tsx | 8 +- .../src/services/movies/queries.ts | 8 +- .../src/components/TodoListCache.tsx | 24 +- .../src/components/TodoListUI.tsx | 11 +- .../src/routes/index.tsx | 9 +- examples/solid/playground/src/index.tsx | 22 +- .../src/routes/character/[id].tsx | 4 +- .../src/routes/index.tsx | 20 +- examples/solid/simple/src/index.tsx | 8 +- .../ssr-astro/src/components/SolidApp.tsx | 64 +- .../src/services/pokemons/queries.ts | 8 +- .../src/components/query-boundary.tsx | 3 +- .../src/routes/hydration.tsx | 25 +- .../src/routes/prefetch.tsx | 8 +- .../solid/suspense/src/components/Project.tsx | 4 +- .../suspense/src/components/Projects.tsx | 17 +- examples/solid/suspense/src/index.tsx | 6 +- .../algolia/src/lib/SearchResults.svelte | 4 +- .../src/routes/+page.svelte | 8 +- .../basic-graphql-request/src/lib/Post.svelte | 4 +- .../src/lib/Posts.svelte | 11 +- .../basic-sveltekit/src/lib/Posts.svelte | 8 +- .../svelte/chat/src/lib/ChatMessage.svelte | 4 +- .../src/lib/ContactForm.svelte | 4 +- .../src/routes/(app)/+layout.ts | 3 +- .../(app)/contacts/[contactId]/+page.svelte | 10 +- .../(app)/contacts/[contactId]/+page.ts | 3 +- .../(app)/contacts/[contactId]/edit/+page.ts | 3 +- .../src/lib/Post.svelte | 8 +- .../src/lib/Posts.svelte | 6 +- .../src/routes/+page.svelte | 17 +- .../src/lib/LoadMore.svelte | 15 +- .../offline-sveltekit/src/lib/queryClient.ts | 8 +- .../src/lib/services/movies/queries.ts | 8 +- .../src/routes/+layout.svelte | 3 +- .../src/routes/[movieId]/+page.svelte | 21 +- .../src/routes/[movieId]/+page.ts | 11 +- .../src/routes/+page.svelte | 18 +- .../src/routes/+page.svelte | 9 +- .../src/routes/+page.svelte | 12 +- .../src/routes/AddTodo.svelte | 8 +- .../src/routes/App.svelte | 4 +- .../src/routes/EditTodo.svelte | 9 +- .../src/routes/TodosList.svelte | 4 +- .../src/lib/CharacterItem.svelte | 17 +- .../src/routes/character/[id]/+page.svelte | 4 +- examples/svelte/simple/src/lib/Simple.svelte | 6 +- .../svelte/ssr-sveltekit/src/lib/Posts.svelte | 8 +- .../svelte/ssr-sveltekit/src/routes/+page.ts | 4 +- .../src/routes/[postId]/+page.ts | 4 +- examples/vue/algolia/src/SearchResults.vue | 14 +- .../vue/auto-refetching-nuxt4/app/app.vue | 25 +- .../basic-graphql-request/src/PostDetail.vue | 19 +- .../basic-graphql-request/src/PostList.vue | 19 +- examples/vue/basic/src/PostDetail.vue | 19 +- examples/vue/basic/src/PostList.vue | 20 +- examples/vue/chat/src/ChatMessage.vue | 12 +- .../src/FavoriteButton.vue | 8 +- .../src/routes/__root.ts | 3 +- .../contacts.$contactId.edit.component.vue | 10 +- .../contacts.$contactId.index.component.vue | 10 +- .../src/routes/contacts.$contactId.route.ts | 3 +- .../src/routes/contacts.new.component.vue | 9 +- .../src/FavoriteButton.vue | 8 +- .../vue/contacts-vue-router/src/router.ts | 16 +- .../src/routes/ContactView.vue | 9 +- .../src/routes/EditView.vue | 9 +- .../src/routes/NewView.vue | 8 +- .../default-query-function/src/PostDetail.vue | 18 +- .../default-query-function/src/PostList.vue | 22 +- .../vue/dependent-queries/src/PostDetail.vue | 14 +- .../vue/dependent-queries/src/PostList.vue | 20 +- examples/vue/devtools-panel/src/App.vue | 12 +- .../app/app.vue | 17 +- .../app/pages/index.vue | 18 +- .../vue/offline-tanstack-router/src/main.ts | 12 +- .../src/queryClient.ts | 8 +- .../src/routes/$movieId.component.vue | 39 +- .../src/routes/$movieId.ts | 6 +- .../src/routes/index.component.vue | 15 +- .../src/services/movies/queries.ts | 8 +- examples/vue/offline-vue-router/src/main.ts | 12 +- .../vue/offline-vue-router/src/queryClient.ts | 8 +- examples/vue/offline-vue-router/src/router.ts | 11 +- .../src/routes/MovieDetailView.vue | 38 +- .../src/routes/MovieListView.vue | 15 +- .../src/services/movies/queries.ts | 8 +- .../app/components/TodoListCache.vue | 26 +- .../app/components/TodoListUI.vue | 9 +- examples/vue/pagination-nuxt4/app/app.vue | 18 +- examples/vue/persister/src/PostDetail.vue | 19 +- examples/vue/persister/src/PostList.vue | 20 +- examples/vue/playground/src/AddTodo.vue | 8 +- examples/vue/playground/src/App.vue | 10 +- examples/vue/playground/src/EditTodo.vue | 25 +- examples/vue/playground/src/TodoList.vue | 16 +- .../app/components/CharacterItem.vue | 12 +- .../app/pages/character/[id].vue | 10 +- .../vue/prefetching-nuxt4/app/pages/index.vue | 18 +- examples/vue/shadow-dom/src/DogList.vue | 11 +- examples/vue/simple-nuxt3/app.vue | 18 +- examples/vue/simple-nuxt4/app/app.vue | 18 +- examples/vue/simple/src/App.vue | 11 +- examples/vue/suspense/src/App.vue | 4 +- .../suspense/src/components/ProjectDetail.vue | 10 +- .../suspense/src/components/ProjectList.vue | 18 +- integrations/lit/vite/src/main.ts | 6 +- integrations/preact/vite/src/App.tsx | 27 +- integrations/query/treeshaking/README.md | 7 + integrations/query/treeshaking/check.ts | 91 + .../query/treeshaking/entries/angular.ts | 1 + integrations/query/treeshaking/entries/lit.ts | 1 + .../query/treeshaking/entries/preact.ts | 1 + .../query/treeshaking/entries/react.ts | 1 + .../query/treeshaking/entries/solid.ts | 1 + .../query/treeshaking/entries/svelte.ts | 1 + integrations/query/treeshaking/entries/vue.ts | 1 + integrations/query/treeshaking/package.json | 32 + integrations/query/treeshaking/tsconfig.json | 13 + integrations/react/bundle-size/.gitignore | 1 + integrations/react/bundle-size/README.md | 71 + integrations/react/bundle-size/analyze.ts | 18 + .../react/bundle-size/browser/apps.test.ts | 152 + .../bundle-size/browser/lazyRoutes.test.ts | 141 + .../bundle-size/browser/microfrontend.test.ts | 43 + .../react/bundle-size/check-editor.ts | 54 + .../react/bundle-size/host/navigation.ts | 24 + integrations/react/bundle-size/index.html | 12 + integrations/react/bundle-size/lazyRoutes.ts | 344 ++ integrations/react/bundle-size/measure.ts | 947 ++++++ .../react/bundle-size/microfrontends.ts | 254 ++ integrations/react/bundle-size/package.json | 30 + .../react/bundle-size/public/books-1.json | 1 + .../react/bundle-size/public/books-2.json | 1 + integrations/react/bundle-size/src/books.ts | 35 + .../react/bundle-size/src/lazy/index.html | 12 + .../react/bundle-size/src/lazy/main.tsx | 80 + integrations/react/bundle-size/src/main.tsx | 13 + .../react/bundle-size/src/numeric-interval.ts | 1 + .../react/bundle-size/src/options.tsx | 68 + .../react/bundle-size/src/paginated.tsx | 52 + .../react/bundle-size/src/polling.tsx | 92 + integrations/react/bundle-size/src/query.tsx | 19 + integrations/react/bundle-size/src/remote.tsx | 16 + .../react/bundle-size/src/screen-types.ts | 6 + .../bundle-size/src/treeshakable-catalog.ts | 10 + .../bundle-size/src/treeshakable-interval.ts | 3 + .../bundle-size/src/treeshakable-options.ts | 16 + .../bundle-size/src/treeshakable-query.ts | 29 + .../react/bundle-size/src/v6-catalog.ts | 8 + .../react/bundle-size/src/v6-options.ts | 8 + .../react/bundle-size/src/v6-query.ts | 14 + integrations/react/bundle-size/tsconfig.json | 22 + .../react/bundle-size/tsconfig.tools.json | 4 + .../bundle-size/tsconfig.treeshakable.json | 15 + .../react/bundle-size/tsconfig.v6.json | 17 + .../bundle-size/vitest.browser.config.ts | 68 + .../react/next-14/app/client-component.tsx | 27 +- integrations/react/next-14/app/page.tsx | 3 +- .../react/next-15/app/client-component.tsx | 39 +- integrations/react/next-15/app/page.tsx | 39 +- .../react/next-16/app/client-component.tsx | 39 +- integrations/react/next-16/app/page.tsx | 39 +- integrations/react/nodenext/README.md | 2 + .../react/nodenext/check-declarations.mjs | 17 + integrations/react/nodenext/package.json | 7 +- integrations/react/nodenext/src/hooks.ts | 12 +- .../react/nodenext/src/sharedTypes.ts | 72 + integrations/react/vite/src/App.tsx | 27 +- integrations/react/webpack-5/src/App.tsx | 27 +- integrations/solid/solid-start-2/src/app.tsx | 9 +- integrations/solid/vite/src/App.tsx | 8 +- .../sveltekit-2/src/routes/+page.svelte | 6 +- integrations/svelte/vite/src/Simple.svelte | 4 +- .../with-persist-query-client.test.ts | 108 +- .../infinite-query-options.test-d.ts | 38 +- .../__tests__/inject-infinite-query.test-d.ts | 12 +- .../src/__tests__/inject-is-fetching.test.ts | 5 +- .../src/__tests__/inject-is-mutating.test.ts | 4 +- .../__tests__/inject-mutation-state.test.ts | 6 +- .../src/__tests__/inject-mutation.test.ts | 75 +- .../src/__tests__/inject-queries.test-d.ts | 5 +- .../src/__tests__/inject-queries.test.ts | 138 +- .../src/__tests__/inject-query.test-d.ts | 14 +- .../src/__tests__/inject-query.test.ts | 106 +- .../src/__tests__/mutation-options.test-d.ts | 11 +- .../src/__tests__/mutation-options.test.ts | 29 +- .../pending-tasks-ssr.zoneful.test.ts | 3 +- .../src/__tests__/pending-tasks.test.ts | 25 +- .../__tests__/provide-tanstack-query.test.ts | 8 +- .../src/__tests__/query-options.test-d.ts | 48 +- .../src/__tests__/upstream-issues.test.ts | 17 +- .../src/__tests__/with-hydration.test.ts | 43 +- .../src/__tests__/zoneful-integration.test.ts | 25 +- .../src/infinite-query-options.ts | 6 +- .../angular-query/src/inject-base-query.ts | 4 +- .../src/inject-infinite-query.ts | 12 +- .../angular-query/src/inject-is-fetching.ts | 10 +- .../angular-query/src/inject-is-mutating.ts | 6 +- .../src/inject-mutation-state.ts | 4 +- packages/angular-query/src/inject-mutation.ts | 16 +- packages/angular-query/src/inject-queries.ts | 25 +- .../angular-query/src/inject-queries.types.ts | 11 +- packages/angular-query/src/inject-query.ts | 18 +- .../angular-query/src/mutation-options.ts | 2 +- packages/angular-query/src/providers.ts | 18 +- packages/angular-query/src/query-options.ts | 6 +- packages/angular-query/src/types.ts | 21 +- .../angular-query/src/utils/result-fields.ts | 75 +- .../__tests__/prefer-query-options.test.ts | 36 + .../prefer-query-options.rule.ts | 56 +- packages/lit-query/src/QueryClientProvider.ts | 5 +- .../src/__tests__/BaseController.test.ts | 4 +- .../src/__tests__/QueryClientProvider.test.ts | 111 +- .../createInfiniteQueryController.test-d.ts | 37 +- .../createInfiniteQueryController.test.ts | 116 +- .../createMutationController.test.ts | 49 +- .../createQueriesController.test-d.ts | 267 +- .../__tests__/createQueriesController.test.ts | 110 +- .../__tests__/createQueryController.test-d.ts | 20 +- .../__tests__/createQueryController.test.ts | 255 +- .../__tests__/infiniteQueryOptions.test-d.ts | 37 +- .../src/__tests__/mutationOptions.test-d.ts | 8 +- .../src/__tests__/mutationOptions.test.ts | 28 +- .../src/__tests__/queryOptions.test-d.ts | 48 +- packages/lit-query/src/__tests__/ssr.test.ts | 36 +- .../src/__tests__/useIsFetching.test.ts | 30 +- .../src/__tests__/useIsMutating.test.ts | 23 +- .../src/__tests__/useMutationState.test.ts | 11 +- .../src/createInfiniteQueryController.ts | 24 +- .../lit-query/src/createMutationController.ts | 4 +- .../lit-query/src/createQueriesController.ts | 39 +- .../lit-query/src/createQueryController.ts | 22 +- packages/lit-query/src/useIsFetching.ts | 5 +- packages/lit-query/src/useIsMutating.ts | 5 +- packages/lit-query/src/useMutationState.ts | 6 +- .../PersistQueryClientProvider.test.tsx | 34 +- .../use-queries-with-persist.test.tsx | 4 +- .../preact-query/src/HydrationBoundary.tsx | 4 +- .../preact-query/src/QueryClientProvider.tsx | 7 +- .../src/QueryErrorResetBoundary.tsx | 12 +- .../src/__tests__/HydrationBoundary.test.tsx | 158 +- .../__tests__/QueryClientProvider.test.tsx | 62 +- .../QueryResetErrorBoundary.test.tsx | 231 +- .../__tests__/fine-grained-persister.test.tsx | 55 +- .../__tests__/infiniteQueryOptions.test-d.tsx | 90 +- .../__tests__/infiniteQueryOptions.test.tsx | 9 +- .../src/__tests__/mutationOptions.test-d.tsx | 11 +- .../src/__tests__/mutationOptions.test.tsx | 13 +- .../src/__tests__/queryOptions.test-d.tsx | 57 +- .../src/__tests__/queryOptions.test.tsx | 6 +- .../src/__tests__/ssr-hydration.test.tsx | 68 +- .../preact-query/src/__tests__/ssr.test.tsx | 63 +- .../src/__tests__/suspense.test.tsx | 30 +- .../src/__tests__/useInfiniteQuery.test-d.tsx | 179 +- .../src/__tests__/useInfiniteQuery.test.tsx | 700 ++-- .../src/__tests__/useIsFetching.test.tsx | 74 +- .../src/__tests__/useMutation.test.tsx | 74 +- .../src/__tests__/useMutationState.test.tsx | 23 +- .../usePrefetchInfiniteQuery.test-d.tsx | 3 +- .../usePrefetchInfiniteQuery.test.tsx | 14 +- .../src/__tests__/usePrefetchQuery.test-d.tsx | 14 +- .../src/__tests__/usePrefetchQuery.test.tsx | 34 +- .../src/__tests__/useQueries.test-d.tsx | 185 +- .../src/__tests__/useQueries.test.tsx | 72 +- .../src/__tests__/useQuery.test-d.tsx | 304 +- .../src/__tests__/useQuery.test.tsx | 2871 +++++++++------- .../useSuspenseInfiniteQuery.test-d.tsx | 151 +- .../useSuspenseInfiniteQuery.test.tsx | 36 +- .../__tests__/useSuspenseQueries.test-d.tsx | 40 +- .../src/__tests__/useSuspenseQueries.test.tsx | 140 +- .../src/__tests__/useSuspenseQuery.test-d.tsx | 140 +- .../src/__tests__/useSuspenseQuery.test.tsx | 405 ++- .../preact-query/src/errorBoundaryUtils.ts | 125 +- packages/preact-query/src/index.ts | 7 +- .../preact-query/src/infiniteQueryOptions.ts | 392 ++- .../preact-query/src/queryBoundaryContext.ts | 7 + packages/preact-query/src/queryDescriptor.ts | 48 + packages/preact-query/src/queryOptions.ts | 328 +- packages/preact-query/src/queryPolicy.ts | 6 + packages/preact-query/src/suspense.ts | 23 +- .../src/suspenseInfiniteQueryOptions.ts | 107 + packages/preact-query/src/suspenseQuery.ts | 52 + .../preact-query/src/suspenseQueryOptions.ts | 70 + packages/preact-query/src/throwOnError.ts | 21 + packages/preact-query/src/types.ts | 87 +- packages/preact-query/src/useBaseQuery.ts | 155 - packages/preact-query/src/useInfiniteQuery.ts | 363 -- packages/preact-query/src/useIsFetching.ts | 10 +- packages/preact-query/src/useMutationState.ts | 8 +- .../preact-query/src/useObserverSnapshot.ts | 41 + .../src/usePrefetchInfiniteQuery.tsx | 12 +- .../preact-query/src/usePrefetchQuery.tsx | 12 +- packages/preact-query/src/useQueries.ts | 107 +- packages/preact-query/src/useQuery.ts | 429 +-- .../src/useSuspenseInfiniteQuery.ts | 203 -- .../preact-query/src/useSuspenseQueries.ts | 49 +- packages/preact-query/src/useSuspenseQuery.ts | 169 - .../src/__tests__/index.test.ts | 47 +- .../src/index.ts | 3 +- packages/query-core/README.md | 51 + .../query-core/src/__tests__/cacheGc.test.tsx | 36 +- .../src/__tests__/cacheOperations.test.ts | 110 + .../src/__tests__/getMutationCache.test.ts | 71 + .../src/__tests__/helpers/descriptors.ts | 11 + .../src/__tests__/helpers/polling.ts | 4 + .../src/__tests__/helpers/projection.ts | 34 + .../src/__tests__/helpers/result.ts | 29 + .../query-core/src/__tests__/helpers/scope.ts | 1 + .../src/__tests__/hydration.test.tsx | 1070 +++--- .../src/__tests__/infiniteQuery.test.ts | 81 + .../__tests__/infiniteQueryBehavior.test.tsx | 56 +- .../infiniteQueryObserver.test-d.tsx | 484 ++- .../__tests__/infiniteQueryObserver.test.tsx | 51 +- .../src/__tests__/mutation.test-d.tsx | 3 +- .../src/__tests__/mutation.test.tsx | 119 +- .../src/__tests__/mutationCache.test-d.tsx | 14 +- .../src/__tests__/mutationCache.test.tsx | 37 +- .../src/__tests__/mutationObserver.test-d.tsx | 11 +- .../src/__tests__/mutationObserver.test.tsx | 40 +- .../src/__tests__/notifyManager.test-d.tsx | 29 +- .../src/__tests__/notifyManager.test.tsx | 4 +- .../src/__tests__/projection.test.ts | 59 + .../src/__tests__/queriesObserver.test-d.tsx | 24 +- .../src/__tests__/queriesObserver.test.tsx | 136 +- .../query-core/src/__tests__/query.test-d.tsx | 527 +-- .../query-core/src/__tests__/query.test.tsx | 602 ++-- .../src/__tests__/queryCache.test-d.tsx | 63 +- .../src/__tests__/queryCache.test.tsx | 409 +-- .../src/__tests__/queryClient.test-d.tsx | 375 +- .../src/__tests__/queryClient.test.tsx | 1027 +++--- .../src/__tests__/queryObserver.test-d.tsx | 504 ++- .../src/__tests__/queryObserver.test.tsx | 378 ++- .../__tests__/queryObserverProjection.test.ts | 81 +- .../queryObserverResultReader.test-d.tsx | 17 +- .../queryObserverResultReader.test.tsx | 100 +- .../src/__tests__/queryResult.test-d.tsx | 60 + .../src/__tests__/queryResult.test.ts | 117 + .../src/__tests__/refetchInterval.test.ts | 152 + .../src/__tests__/serialScope.test.ts | 68 + .../src/__tests__/streamedQuery.test-d.tsx | 1 - .../src/__tests__/streamedQuery.test.tsx | 59 +- .../query-core/src/__tests__/utils.test-d.tsx | 19 +- .../query-core/src/__tests__/utils.test.tsx | 11 +- packages/query-core/src/cacheOperations.ts | 280 ++ packages/query-core/src/eventManager.ts | 45 + packages/query-core/src/fetchOptimistic.ts | 62 + packages/query-core/src/focusManager.ts | 83 +- packages/query-core/src/hydration.ts | 210 +- packages/query-core/src/index.ts | 239 +- packages/query-core/src/infiniteQuery.ts | 105 + .../query-core/src/infiniteQueryBehavior.ts | 249 +- .../query-core/src/infiniteQueryObserver.ts | 59 +- packages/query-core/src/mutation.ts | 210 +- packages/query-core/src/mutationCache.ts | 117 +- packages/query-core/src/mutationObserver.ts | 68 +- packages/query-core/src/notifyManager.ts | 54 +- packages/query-core/src/onlineManager.ts | 76 +- packages/query-core/src/placeholderData.ts | 98 + packages/query-core/src/projectResult.ts | 89 + packages/query-core/src/projectionTypes.ts | 20 + packages/query-core/src/queriesObserver.ts | 126 +- packages/query-core/src/query.ts | 791 ++--- packages/query-core/src/queryCache.ts | 178 +- .../query-core/src/queryCacheOperations.ts | 81 + packages/query-core/src/queryClient.ts | 1662 ++++----- packages/query-core/src/queryObserver.ts | 428 +-- packages/query-core/src/queryPredicates.ts | 94 + packages/query-core/src/queryResult.ts | 182 + packages/query-core/src/queryState.ts | 82 + packages/query-core/src/refetchInterval.ts | 101 + packages/query-core/src/select.ts | 131 + packages/query-core/src/serialScope.ts | 96 + packages/query-core/src/streamedQuery.ts | 52 +- packages/query-core/src/timeoutManager.ts | 2 +- packages/query-core/src/types.ts | 574 +--- packages/query-core/src/utils.ts | 46 +- packages/query-core/tsdown.config.ts | 5 +- packages/query-devtools/src/Devtools.tsx | 69 +- packages/query-devtools/src/Explorer.tsx | 13 +- .../src/__tests__/Devtools.test.tsx | 175 +- .../src/__tests__/DevtoolsComponent.test.tsx | 8 +- .../__tests__/DevtoolsPanelComponent.test.tsx | 8 +- .../src/__tests__/Explorer.test.tsx | 202 +- .../contexts/QueryDevtoolsContext.test.tsx | 10 +- .../src/__tests__/utils.test.ts | 34 +- packages/query-devtools/src/utils.tsx | 9 +- .../src/__tests__/createPersister.test.ts | 117 +- .../src/__tests__/persist.test.ts | 19 +- .../src/__tests__/retryStrategies.test.ts | 12 +- .../src/createPersister.ts | 25 +- .../query-persist-client-core/src/persist.ts | 29 +- packages/query-test-utils/src/index.ts | 1 + .../src/queryResultSnapshot.ts | 73 + .../src/ReactQueryStreamedHydration.tsx | 3 +- .../src/PersistQueryClientProvider.tsx | 41 +- .../PersistQueryClientProvider.test.tsx | 230 +- .../use-queries-with-persist.test.tsx | 4 +- packages/react-query/README.md | 292 ++ .../react-query/src/HydrationBoundary.tsx | 13 +- .../react-query/src/QueryClientProvider.tsx | 7 +- .../src/QueryErrorResetBoundary.tsx | 3 +- .../src/__tests__/Activity.test.tsx | 43 +- .../src/__tests__/HydrationBoundary.test.tsx | 186 +- .../__tests__/QueryClientProvider.test.tsx | 62 +- .../QueryResetErrorBoundary.test.tsx | 245 +- .../__tests__/fine-grained-persister.test.tsx | 55 +- .../src/__tests__/helpers/projection.ts | 34 + .../src/__tests__/helpers/result.ts | 4 + .../__tests__/infiniteQueryOptions.test-d.tsx | 102 +- .../__tests__/infiniteQueryOptions.test.tsx | 6 +- .../src/__tests__/mutationOptions.test-d.tsx | 11 +- .../src/__tests__/mutationOptions.test.tsx | 13 +- .../src/__tests__/placeholderData.test.ts | 39 +- .../src/__tests__/projection.test-d.ts | 81 + .../src/__tests__/queryBuilders.test.ts | 45 + .../src/__tests__/queryModes.test-d.ts | 250 ++ .../src/__tests__/queryModes.test.tsx | 244 ++ .../src/__tests__/queryOptions.test-d.tsx | 63 +- .../src/__tests__/queryOptions.test.tsx | 6 +- .../src/__tests__/refetchInterval.test-d.ts | 67 + .../src/__tests__/sharedCore.test.ts | 45 + .../src/__tests__/ssr-hydration.test.tsx | 77 +- .../react-query/src/__tests__/ssr.test.tsx | 77 +- .../src/__tests__/suspense.test.tsx | 43 +- .../src/__tests__/transition.test.tsx | 130 +- .../src/__tests__/useInfiniteQuery.test-d.tsx | 173 +- .../src/__tests__/useInfiniteQuery.test.tsx | 718 ++-- .../src/__tests__/useIsFetching.test.tsx | 74 +- .../src/__tests__/useMutation.test.tsx | 74 +- .../src/__tests__/useMutationState.test.tsx | 23 +- .../usePrefetchInfiniteQuery.test-d.tsx | 3 +- .../usePrefetchInfiniteQuery.test.tsx | 14 +- .../src/__tests__/usePrefetchQuery.test-d.tsx | 14 +- .../src/__tests__/usePrefetchQuery.test.tsx | 34 +- .../src/__tests__/useQueries.test-d.tsx | 262 +- .../src/__tests__/useQueries.test.tsx | 47 +- .../src/__tests__/useQuery.test-d.tsx | 316 +- .../src/__tests__/useQuery.test.tsx | 3014 ++++++++++------- .../useSuspenseInfiniteQuery.test-d.tsx | 189 +- .../useSuspenseInfiniteQuery.test.tsx | 93 +- .../__tests__/useSuspenseQueries.test-d.tsx | 135 +- .../src/__tests__/useSuspenseQueries.test.tsx | 170 +- .../src/__tests__/useSuspenseQuery.test-d.tsx | 167 +- .../src/__tests__/useSuspenseQuery.test.tsx | 463 ++- .../react-query/src/errorBoundaryUtils.ts | 126 +- packages/react-query/src/index.ts | 238 +- .../react-query/src/infiniteQueryOptions.ts | 392 ++- packages/react-query/src/mutationOptions.ts | 168 +- packages/react-query/src/queryDescriptor.ts | 48 + packages/react-query/src/queryOptions.ts | 328 +- packages/react-query/src/queryPolicy.ts | 6 + packages/react-query/src/suspense.ts | 39 +- .../src/suspenseInfiniteQueryOptions.ts | 107 + packages/react-query/src/suspenseQuery.ts | 52 + .../react-query/src/suspenseQueryOptions.ts | 70 + packages/react-query/src/throwOnError.ts | 19 + packages/react-query/src/types.ts | 78 +- packages/react-query/src/useBaseQuery.ts | 155 - packages/react-query/src/useInfiniteQuery.ts | 364 -- packages/react-query/src/useIsFetching.ts | 12 +- packages/react-query/src/useMutation.ts | 29 +- packages/react-query/src/useMutationState.ts | 9 +- .../react-query/src/useObserverSnapshot.ts | 42 + .../src/usePrefetchInfiniteQuery.tsx | 12 +- packages/react-query/src/usePrefetchQuery.tsx | 12 +- packages/react-query/src/useQueries.ts | 121 +- packages/react-query/src/useQuery.ts | 427 +-- .../src/useSuspenseInfiniteQuery.ts | 184 - .../react-query/src/useSuspenseQueries.ts | 62 +- packages/react-query/src/useSuspenseQuery.ts | 150 - packages/react-query/tsdown.config.ts | 8 +- .../PersistQueryClientProvider.test.tsx | 74 +- .../solid-query/src/QueryClientProvider.tsx | 8 +- .../__tests__/QueryClientProvider.test.tsx | 22 +- .../__tests__/infiniteQueryOptions.test-d.tsx | 18 +- .../src/__tests__/mutationOptions.test-d.tsx | 11 +- .../src/__tests__/mutationOptions.test.tsx | 31 +- .../src/__tests__/queryOptions.test-d.tsx | 42 +- .../src/__tests__/suspense.test.tsx | 23 +- .../src/__tests__/transition.test.tsx | 3 +- .../src/__tests__/useInfiniteQuery.test-d.tsx | 29 +- .../src/__tests__/useInfiniteQuery.test.tsx | 373 +- .../src/__tests__/useIsFetching.test.tsx | 9 +- .../src/__tests__/useIsMutating.test.tsx | 14 +- .../src/__tests__/useMutation.test.tsx | 56 +- .../src/__tests__/useMutationState.test.tsx | 3 +- .../src/__tests__/useQueries.test-d.tsx | 150 +- .../src/__tests__/useQueries.test.tsx | 7 +- .../src/__tests__/useQuery.test-d.tsx | 5 +- .../src/__tests__/useQuery.test.tsx | 517 +-- .../solid-query/src/infiniteQueryOptions.ts | 4 +- packages/solid-query/src/queryOptions.ts | 4 +- packages/solid-query/src/useBaseQuery.ts | 24 +- packages/solid-query/src/useInfiniteQuery.ts | 4 +- packages/solid-query/src/useIsFetching.ts | 11 +- packages/solid-query/src/useIsMutating.ts | 9 +- packages/solid-query/src/useMutation.ts | 18 +- packages/solid-query/src/useMutationState.ts | 4 +- packages/solid-query/src/useQueries.ts | 32 +- packages/solid-query/src/useQuery.ts | 6 +- .../PersistQueryClientProvider.svelte.test.ts | 79 +- .../src/QueryClientProvider.svelte | 10 +- .../src/createBaseQuery.svelte.ts | 3 +- .../svelte-query/src/createInfiniteQuery.ts | 6 +- .../svelte-query/src/createMutation.svelte.ts | 18 +- .../svelte-query/src/createQueries.svelte.ts | 24 +- packages/svelte-query/src/createQuery.ts | 6 +- .../svelte-query/src/infiniteQueryOptions.ts | 4 +- packages/svelte-query/src/queryOptions.ts | 4 +- packages/svelte-query/src/useHydrate.ts | 2 +- .../svelte-query/src/useIsFetching.svelte.ts | 5 +- .../svelte-query/src/useIsMutating.svelte.ts | 5 +- .../src/useMutationState.svelte.ts | 4 +- packages/svelte-query/src/useQueryClient.ts | 2 +- .../HydrationBoundary.svelte.test.ts | 22 +- .../QueryClientProvider.svelte.test.ts | 15 +- .../createInfiniteQuery/ChangeClient.svelte | 4 +- .../tests/createInfiniteQuery/Options.svelte | 5 +- .../tests/createInfiniteQuery/Select.svelte | 12 +- .../createInfiniteQuery.svelte.test.ts | 21 +- .../createInfiniteQuery.test-d.ts | 31 +- .../InvalidateFromContext.svelte | 3 +- .../createMutation/MutationFnContext.svelte | 3 +- .../createMutation/OptimisticUpdate.svelte | 13 +- .../createMutation.svelte.test.ts | 29 +- .../createQueries.svelte.test.ts | 3 +- .../createQueries/createQueries.test-d.ts | 140 +- .../tests/createQuery/Base.svelte | 17 +- .../tests/createQuery/Counter.svelte | 5 +- .../tests/createQuery/TwoQueries.svelte | 5 +- .../createQuery/createQuery.svelte.test.ts | 149 +- .../tests/createQuery/createQuery.test-d.ts | 5 +- .../tests/infiniteQueryOptions.test-d.ts | 26 +- .../tests/mutationOptions/Base.svelte | 17 +- .../tests/mutationOptions/Multi.svelte | 17 +- .../mutationOptions.svelte.test.ts | 4 +- .../mutationOptions/mutationOptions.test-d.ts | 11 +- .../svelte-query/tests/queryOptions.test-d.ts | 48 +- .../useIsFetching.svelte.test.ts | 4 +- .../useIsMutating.svelte.test.ts | 4 +- .../useMutationState.svelte.test.ts | 4 +- .../__tests__/infiniteQueryOptions.test-d.ts | 30 +- .../src/__tests__/mutationOptions.test-d.ts | 7 +- .../src/__tests__/mutationOptions.test.ts | 52 +- .../src/__tests__/queryCache.test.ts | 20 +- ...yClient.shared-execution-options.test-d.ts | 19 +- .../src/__tests__/queryClient.test-d.ts | 88 +- .../src/__tests__/queryClient.test.ts | 252 +- .../src/__tests__/queryOptions.test-d.ts | 67 +- .../src/__tests__/useInfiniteQuery.test-d.tsx | 15 +- .../src/__tests__/useInfiniteQuery.test.ts | 18 +- .../src/__tests__/useIsFetching.test.ts | 6 +- .../src/__tests__/useIsMutating.test.ts | 6 +- .../src/__tests__/useMutation.test.ts | 58 +- .../src/__tests__/useMutationState.test.ts | 3 +- .../usePrefetchInfiniteQuery.test-d.ts | 4 +- .../usePrefetchInfiniteQuery.test.ts | 21 +- .../src/__tests__/usePrefetchQuery.test-d.ts | 4 +- .../src/__tests__/usePrefetchQuery.test.ts | 21 +- .../src/__tests__/useQueries.test-d.ts | 11 +- .../src/__tests__/useQueries.test.ts | 29 +- .../src/__tests__/useQuery.test-d.ts | 47 +- .../vue-query/src/__tests__/useQuery.test.ts | 182 +- .../src/__tests__/vueQueryPlugin.test.ts | 57 +- packages/vue-query/src/devtools/devtools.ts | 19 +- packages/vue-query/src/devtools/utils.ts | 5 +- packages/vue-query/src/index.ts | 25 +- .../vue-query/src/infiniteQueryOptions.ts | 4 +- packages/vue-query/src/queryCache.ts | 49 +- packages/vue-query/src/queryClient.ts | 1004 +++--- packages/vue-query/src/queryOptions.ts | 10 +- packages/vue-query/src/useBaseQuery.ts | 29 +- packages/vue-query/src/useIsFetching.ts | 9 +- packages/vue-query/src/useMutation.ts | 26 +- packages/vue-query/src/useMutationState.ts | 3 +- .../vue-query/src/usePrefetchInfiniteQuery.ts | 11 +- packages/vue-query/src/usePrefetchQuery.ts | 11 +- packages/vue-query/src/useQueries.ts | 36 +- packages/vue-query/src/useQuery.ts | 2 +- packages/vue-query/src/useQueryClient.ts | 2 +- packages/vue-query/src/vueQueryPlugin.ts | 10 +- pnpm-lock.yaml | 254 +- 792 files changed, 30961 insertions(+), 20699 deletions(-) create mode 100644 .changeset/treeshakable-query.md create mode 100644 .github/workflows/query-bundle-size.yml create mode 100644 docs/framework/react/guides/migrating-to-v6.md create mode 100644 integrations/query/treeshaking/README.md create mode 100644 integrations/query/treeshaking/check.ts create mode 100644 integrations/query/treeshaking/entries/angular.ts create mode 100644 integrations/query/treeshaking/entries/lit.ts create mode 100644 integrations/query/treeshaking/entries/preact.ts create mode 100644 integrations/query/treeshaking/entries/react.ts create mode 100644 integrations/query/treeshaking/entries/solid.ts create mode 100644 integrations/query/treeshaking/entries/svelte.ts create mode 100644 integrations/query/treeshaking/entries/vue.ts create mode 100644 integrations/query/treeshaking/package.json create mode 100644 integrations/query/treeshaking/tsconfig.json create mode 100644 integrations/react/bundle-size/.gitignore create mode 100644 integrations/react/bundle-size/README.md create mode 100644 integrations/react/bundle-size/analyze.ts create mode 100644 integrations/react/bundle-size/browser/apps.test.ts create mode 100644 integrations/react/bundle-size/browser/lazyRoutes.test.ts create mode 100644 integrations/react/bundle-size/browser/microfrontend.test.ts create mode 100644 integrations/react/bundle-size/check-editor.ts create mode 100644 integrations/react/bundle-size/host/navigation.ts create mode 100644 integrations/react/bundle-size/index.html create mode 100644 integrations/react/bundle-size/lazyRoutes.ts create mode 100644 integrations/react/bundle-size/measure.ts create mode 100644 integrations/react/bundle-size/microfrontends.ts create mode 100644 integrations/react/bundle-size/package.json create mode 100644 integrations/react/bundle-size/public/books-1.json create mode 100644 integrations/react/bundle-size/public/books-2.json create mode 100644 integrations/react/bundle-size/src/books.ts create mode 100644 integrations/react/bundle-size/src/lazy/index.html create mode 100644 integrations/react/bundle-size/src/lazy/main.tsx create mode 100644 integrations/react/bundle-size/src/main.tsx create mode 100644 integrations/react/bundle-size/src/numeric-interval.ts create mode 100644 integrations/react/bundle-size/src/options.tsx create mode 100644 integrations/react/bundle-size/src/paginated.tsx create mode 100644 integrations/react/bundle-size/src/polling.tsx create mode 100644 integrations/react/bundle-size/src/query.tsx create mode 100644 integrations/react/bundle-size/src/remote.tsx create mode 100644 integrations/react/bundle-size/src/screen-types.ts create mode 100644 integrations/react/bundle-size/src/treeshakable-catalog.ts create mode 100644 integrations/react/bundle-size/src/treeshakable-interval.ts create mode 100644 integrations/react/bundle-size/src/treeshakable-options.ts create mode 100644 integrations/react/bundle-size/src/treeshakable-query.ts create mode 100644 integrations/react/bundle-size/src/v6-catalog.ts create mode 100644 integrations/react/bundle-size/src/v6-options.ts create mode 100644 integrations/react/bundle-size/src/v6-query.ts create mode 100644 integrations/react/bundle-size/tsconfig.json create mode 100644 integrations/react/bundle-size/tsconfig.tools.json create mode 100644 integrations/react/bundle-size/tsconfig.treeshakable.json create mode 100644 integrations/react/bundle-size/tsconfig.v6.json create mode 100644 integrations/react/bundle-size/vitest.browser.config.ts create mode 100644 integrations/react/nodenext/check-declarations.mjs create mode 100644 integrations/react/nodenext/src/sharedTypes.ts create mode 100644 packages/preact-query/src/queryBoundaryContext.ts create mode 100644 packages/preact-query/src/queryDescriptor.ts create mode 100644 packages/preact-query/src/queryPolicy.ts create mode 100644 packages/preact-query/src/suspenseInfiniteQueryOptions.ts create mode 100644 packages/preact-query/src/suspenseQuery.ts create mode 100644 packages/preact-query/src/suspenseQueryOptions.ts create mode 100644 packages/preact-query/src/throwOnError.ts delete mode 100644 packages/preact-query/src/useBaseQuery.ts delete mode 100644 packages/preact-query/src/useInfiniteQuery.ts create mode 100644 packages/preact-query/src/useObserverSnapshot.ts delete mode 100644 packages/preact-query/src/useSuspenseInfiniteQuery.ts delete mode 100644 packages/preact-query/src/useSuspenseQuery.ts create mode 100644 packages/query-core/README.md create mode 100644 packages/query-core/src/__tests__/cacheOperations.test.ts create mode 100644 packages/query-core/src/__tests__/getMutationCache.test.ts create mode 100644 packages/query-core/src/__tests__/helpers/descriptors.ts create mode 100644 packages/query-core/src/__tests__/helpers/polling.ts create mode 100644 packages/query-core/src/__tests__/helpers/projection.ts create mode 100644 packages/query-core/src/__tests__/helpers/result.ts create mode 100644 packages/query-core/src/__tests__/helpers/scope.ts create mode 100644 packages/query-core/src/__tests__/infiniteQuery.test.ts create mode 100644 packages/query-core/src/__tests__/projection.test.ts create mode 100644 packages/query-core/src/__tests__/queryResult.test-d.tsx create mode 100644 packages/query-core/src/__tests__/queryResult.test.ts create mode 100644 packages/query-core/src/__tests__/refetchInterval.test.ts create mode 100644 packages/query-core/src/__tests__/serialScope.test.ts create mode 100644 packages/query-core/src/cacheOperations.ts create mode 100644 packages/query-core/src/eventManager.ts create mode 100644 packages/query-core/src/fetchOptimistic.ts create mode 100644 packages/query-core/src/infiniteQuery.ts create mode 100644 packages/query-core/src/placeholderData.ts create mode 100644 packages/query-core/src/projectResult.ts create mode 100644 packages/query-core/src/projectionTypes.ts create mode 100644 packages/query-core/src/queryCacheOperations.ts create mode 100644 packages/query-core/src/queryPredicates.ts create mode 100644 packages/query-core/src/queryResult.ts create mode 100644 packages/query-core/src/queryState.ts create mode 100644 packages/query-core/src/refetchInterval.ts create mode 100644 packages/query-core/src/select.ts create mode 100644 packages/query-core/src/serialScope.ts create mode 100644 packages/query-test-utils/src/queryResultSnapshot.ts create mode 100644 packages/react-query/src/__tests__/helpers/projection.ts create mode 100644 packages/react-query/src/__tests__/helpers/result.ts create mode 100644 packages/react-query/src/__tests__/projection.test-d.ts create mode 100644 packages/react-query/src/__tests__/queryBuilders.test.ts create mode 100644 packages/react-query/src/__tests__/queryModes.test-d.ts create mode 100644 packages/react-query/src/__tests__/queryModes.test.tsx create mode 100644 packages/react-query/src/__tests__/refetchInterval.test-d.ts create mode 100644 packages/react-query/src/__tests__/sharedCore.test.ts create mode 100644 packages/react-query/src/queryDescriptor.ts create mode 100644 packages/react-query/src/queryPolicy.ts create mode 100644 packages/react-query/src/suspenseInfiniteQueryOptions.ts create mode 100644 packages/react-query/src/suspenseQuery.ts create mode 100644 packages/react-query/src/suspenseQueryOptions.ts create mode 100644 packages/react-query/src/throwOnError.ts delete mode 100644 packages/react-query/src/useBaseQuery.ts delete mode 100644 packages/react-query/src/useInfiniteQuery.ts create mode 100644 packages/react-query/src/useObserverSnapshot.ts delete mode 100644 packages/react-query/src/useSuspenseInfiniteQuery.ts delete mode 100644 packages/react-query/src/useSuspenseQuery.ts diff --git a/.changeset/treeshakable-query.md b/.changeset/treeshakable-query.md new file mode 100644 index 00000000000..ec3b6c39b21 --- /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. 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..520fad07895 100644 --- a/.size-limit.json +++ b/.size-limit.json @@ -9,7 +9,7 @@ "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"] } ] 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/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..8db214410d7 100644 --- a/docs/framework/angular/guides/query-options.md +++ b/docs/framework/angular/guides/query-options.md @@ -7,7 +7,7 @@ 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,20 +38,22 @@ 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 { 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, + select: select((data) => data.title), })) ``` diff --git a/docs/framework/preact/quick-start.md b/docs/framework/preact/quick-start.md index 9f84f255255..a9894306fd7 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,14 @@ 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..2efa5a240e4 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..2925e315a4f 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 queryResult = useQuery( + infiniteQueryOptions({ + queryKey: ['projects'], + queryFn: fetchProjects, + initialPageParam: 0, + getNextPageParam: (lastPage, pages) => lastPage.nextCursor, + }), + ) - return status === 'pending' ? ( + return queryResult.status === 'pending' ? (

Loading...

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

Error: {error.message}

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

Error: {queryResult.error.message}

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

{project.name}

@@ -81,17 +80,21 @@ function Projects() { ))}
-
{isFetching && !isFetchingNextPage ? 'Fetching...' : null}
+
+ {isFetching(queryResult) && !isFetchingNextPage(queryResult) + ? 'Fetching...' + : null} +
) } @@ -126,13 +129,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 +149,19 @@ 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..226aa13e276 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 `suspenseQueryOptions` instance. [//]: # '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..63eef027cb1 100644 --- a/docs/framework/react/guides/polling.md +++ b/docs/framework/react/guides/polling.md @@ -3,16 +3,18 @@ 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({ +import { queryOptions, refetchInterval, useQuery } from '@tanstack/react-query' + +useQuery(queryOptions({ queryKey: ['prices'], queryFn: fetchPrices, - refetchInterval: 5 * 1000, // every 5 seconds -}) + refetchInterval: refetchInterval(5 * 1000), // every 5 seconds +})) ``` [//]: # 'Example1' @@ -26,15 +28,17 @@ Pass a function instead of a number to compute the interval from the current que [//]: # 'Example2' ```tsx -useQuery({ +import { queryOptions, refetchInterval, useQuery } from '@tanstack/react-query' + +useQuery(queryOptions({ 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 - }, -}) + }), +})) ``` [//]: # 'Example2' @@ -48,12 +52,14 @@ By default, polling pauses when the browser tab loses focus. For dashboards or a [//]: # 'Example3' ```tsx -useQuery({ +import { queryOptions, refetchInterval, useQuery } from '@tanstack/react-query' + +useQuery(queryOptions({ queryKey: ['portfolio'], queryFn: fetchPortfolio, - refetchInterval: 30 * 1000, + refetchInterval: refetchInterval(30 * 1000), refetchIntervalInBackground: true, -}) +})) ``` [//]: # 'Example3' @@ -65,14 +71,16 @@ Pass a function to `refetchInterval` and close over component state to control w [//]: # 'Example4' ```tsx -useQuery({ +import { queryOptions, refetchInterval, useQuery } from '@tanstack/react-query' + +useQuery(queryOptions({ queryKey: ['prices', tokenAddress], queryFn: () => fetchPrice(tokenAddress), - refetchInterval: () => { + refetchInterval: refetchInterval(() => { if (!tokenAddress || isPaused) return false return 15 * 1000 - }, -}) + }), +})) ``` [//]: # 'Example4' @@ -84,12 +92,14 @@ TanStack Query detects connectivity by listening to the browser's `online` and ` [//]: # 'Example5' ```tsx -useQuery({ +import { queryOptions, refetchInterval, useQuery } from '@tanstack/react-query' + +useQuery(queryOptions({ queryKey: ['chainStatus'], queryFn: fetchChainStatus, - refetchInterval: 10 * 1000, + refetchInterval: refetchInterval(10 * 1000), networkMode: 'always', -}) +})) ``` [//]: # 'Example5' @@ -98,7 +108,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..76b765902ae 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,10 @@ 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 +37,7 @@ 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 +59,26 @@ 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({ + 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 +94,10 @@ If booleans aren't your thing, you can always use the `status` state as well: ```tsx function Todos() { - const { status, data, error } = useQuery({ + 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..4fb18c2ddf6 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/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/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/ssr/server/index.mjs b/examples/lit/ssr/server/index.mjs index 9c817db5835..8a705cd50db 100644 --- a/examples/lit/ssr/server/index.mjs +++ b/examples/lit/ssr/server/index.mjs @@ -1,3 +1,4 @@ +import { query } from '@tanstack/lit-query' import { readFile } from 'node:fs/promises' import { createServer } from 'node:http' import { dirname, extname, resolve, sep } from 'node:path' @@ -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}

@@ -185,7 +189,7 @@ function Todos({ const [filter, setFilter] = useState(initialFilter) const { status, data, isFetching, error, failureCount, refetch } = useQuery( - todosQueries.list(filter), + queryOptions(todosQueries.list(filter)), ) return ( @@ -242,7 +246,7 @@ function EditTodo({ const queryClient = useQueryClient() const { status, data, isFetching, failureCount, refetch } = useQuery( - todosQueries.detail(editingIndex), + queryOptions(todosQueries.detail(editingIndex)), ) const [draft, setDraft] = useState>>({}) @@ -251,8 +255,12 @@ 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({}) }, }) @@ -338,7 +346,7 @@ function AddTodo() { const addMutation = useMutation({ ...todosMutations.create(), onSuccess: () => { - queryClient.invalidateQueries({ queryKey: todosQueries.lists() }) + invalidateQueries(queryClient, { queryKey: todosQueries.lists() }) }, }) diff --git a/examples/preact/prefetching-preact-iso/src/Character.tsx b/examples/preact/prefetching-preact-iso/src/Character.tsx index 6871f5609f7..bd15436b1a3 100644 --- a/examples/preact/prefetching-preact-iso/src/Character.tsx +++ b/examples/preact/prefetching-preact-iso/src/Character.tsx @@ -1,4 +1,4 @@ -import { useQuery } from '@tanstack/preact-query' +import { queryOptions, useQuery } from '@tanstack/preact-query' import { useRoute } from 'preact-iso' import { charactersQueries } from './services/characters/queries' @@ -8,7 +8,7 @@ export default function CharacterPage() { const isValidId = /^\d+$/.test(params.id) && id > 0 const { status, data, error, isFetching } = useQuery( - charactersQueries.detail(isValidId ? id : undefined), + queryOptions(charactersQueries.detail(isValidId ? id : undefined)), ) return ( diff --git a/examples/preact/prefetching-preact-iso/src/Home.tsx b/examples/preact/prefetching-preact-iso/src/Home.tsx index e1c62946327..1009b9cf8ec 100644 --- a/examples/preact/prefetching-preact-iso/src/Home.tsx +++ b/examples/preact/prefetching-preact-iso/src/Home.tsx @@ -1,4 +1,12 @@ -import { noop, useQuery, useQueryClient } from '@tanstack/preact-query' +import { + queryOptions, + query, + isPending, + isError, + noop, + useQuery, + useQueryClient, +} from '@tanstack/preact-query' import { PreactQueryDevtools } from '@tanstack/preact-query-devtools' import { useState } from 'preact/hooks' import { charactersQueries } from './services/characters/queries' @@ -13,18 +21,18 @@ function CharacterItem({ }) { const queryClient = useQueryClient() - const { data } = useQuery({ - ...charactersQueries.detail(char.id), - enabled: false, - }) + const { data } = useQuery( + queryOptions({ + ...charactersQueries.detail(char.id), + enabled: false, + }), + ) const prefetch = () => { - queryClient - .query({ - ...charactersQueries.detail(char.id), - staleTime: 10 * 1000, // only prefetch if older than 10 seconds - }) - .catch(noop) + query(queryClient, { + ...charactersQueries.detail(char.id), + staleTime: 10 * 1000, // only prefetch if older than 10 seconds + }).catch(noop) } return ( @@ -46,9 +54,11 @@ function CharacterItem({ export default function Home() { const [selectedChar, setSelectedChar] = useState(1) - const charactersQuery = useQuery(charactersQueries.list()) + const charactersQuery = useQuery(queryOptions(charactersQueries.list())) - const characterQuery = useQuery(charactersQueries.detail(selectedChar)) + const characterQuery = useQuery( + queryOptions(charactersQueries.detail(selectedChar)), + ) return (
@@ -59,9 +69,9 @@ export default function Home() { details page will render it without a loading state.

Characters

- {charactersQuery.isPending ? ( + {isPending(charactersQuery) ? ( 'Loading...' - ) : charactersQuery.isError ? ( + ) : isError(charactersQuery) ? ( Error: {charactersQuery.error.message} ) : ( <> @@ -76,9 +86,9 @@ export default function Home() {

Selected Character

- {characterQuery.isPending ? ( + {isPending(characterQuery) ? ( 'Loading...' - ) : characterQuery.isError ? ( + ) : isError(characterQuery) ? ( Error: {characterQuery.error.message} ) : ( <> diff --git a/examples/preact/rick-morty-preact-iso/src/Character.tsx b/examples/preact/rick-morty-preact-iso/src/Character.tsx index 3c1c15bc4ea..83cfec6d5d3 100644 --- a/examples/preact/rick-morty-preact-iso/src/Character.tsx +++ b/examples/preact/rick-morty-preact-iso/src/Character.tsx @@ -1,4 +1,4 @@ -import { useQuery } from '@tanstack/preact-query' +import { queryOptions, useQuery } from '@tanstack/preact-query' import { useRoute } from 'preact-iso' import { charactersQueries } from './services/characters/queries' import { episodesQueries } from './services/episodes/queries' @@ -8,7 +8,9 @@ function Character() { const { params } = useRoute() const characterId = params.characterId - const { status, data } = useQuery(charactersQueries.detail(characterId)) + const { status, data } = useQuery( + queryOptions(charactersQueries.detail(characterId)), + ) if (status === 'pending') return

Loading...

if (status === 'error') return

Error :(

@@ -47,7 +49,9 @@ function Character() { } function Episode({ episodeId }: { episodeId: string }) { - const { data, status } = useQuery(episodesQueries.detail(episodeId)) + const { data, status } = useQuery( + queryOptions(episodesQueries.detail(episodeId)), + ) if (status === 'success') { return ( @@ -66,7 +70,9 @@ function Episode({ episodeId }: { episodeId: string }) { } function Location({ locationId }: { locationId: string }) { - const { data, status } = useQuery(locationsQueries.detail(locationId)) + const { data, status } = useQuery( + queryOptions(locationsQueries.detail(locationId)), + ) if (status === 'pending') return Loading... if (status === 'error') return Error :( diff --git a/examples/preact/rick-morty-preact-iso/src/Characters.tsx b/examples/preact/rick-morty-preact-iso/src/Characters.tsx index b9832bab0fb..c05dfdb83f4 100644 --- a/examples/preact/rick-morty-preact-iso/src/Characters.tsx +++ b/examples/preact/rick-morty-preact-iso/src/Characters.tsx @@ -1,8 +1,8 @@ -import { useQuery } from '@tanstack/preact-query' +import { queryOptions, useQuery } from '@tanstack/preact-query' import { charactersQueries } from './services/characters/queries' export default function Characters() { - const { status, data } = useQuery(charactersQueries.list()) + const { status, data } = useQuery(queryOptions(charactersQueries.list())) if (status === 'pending') return

Loading...

if (status === 'error') return

Error :(

diff --git a/examples/preact/rick-morty-preact-iso/src/Episode.tsx b/examples/preact/rick-morty-preact-iso/src/Episode.tsx index aaf5228b4c0..7eba5d5c232 100644 --- a/examples/preact/rick-morty-preact-iso/src/Episode.tsx +++ b/examples/preact/rick-morty-preact-iso/src/Episode.tsx @@ -1,4 +1,4 @@ -import { useQuery } from '@tanstack/preact-query' +import { queryOptions, useQuery } from '@tanstack/preact-query' import { useRoute } from 'preact-iso' import { charactersQueries } from './services/characters/queries' import { episodesQueries } from './services/episodes/queries' @@ -7,7 +7,9 @@ function Episode() { const { params } = useRoute() const episodeId = params.episodeId - const { data, status } = useQuery(episodesQueries.detail(episodeId)) + const { data, status } = useQuery( + queryOptions(episodesQueries.detail(episodeId)), + ) if (status === 'pending') return

Loading...

@@ -29,7 +31,9 @@ function Episode() { } function Character({ characterId }: { characterId: string }) { - const { data, status } = useQuery(charactersQueries.detail(characterId)) + const { data, status } = useQuery( + queryOptions(charactersQueries.detail(characterId)), + ) if (status === 'pending') return

Loading...

if (status === 'error') return

Error :(

diff --git a/examples/preact/rick-morty-preact-iso/src/Episodes.tsx b/examples/preact/rick-morty-preact-iso/src/Episodes.tsx index c170a03b6f6..34d5390d920 100644 --- a/examples/preact/rick-morty-preact-iso/src/Episodes.tsx +++ b/examples/preact/rick-morty-preact-iso/src/Episodes.tsx @@ -1,8 +1,8 @@ -import { useQuery } from '@tanstack/preact-query' +import { queryOptions, useQuery } from '@tanstack/preact-query' import { episodesQueries } from './services/episodes/queries' export default function Episodes() { - const { data, status } = useQuery(episodesQueries.list()) + const { data, status } = useQuery(queryOptions(episodesQueries.list())) if (status === 'pending') { return

Loading...

diff --git a/examples/preact/shadow-dom/src/DogList.tsx b/examples/preact/shadow-dom/src/DogList.tsx index 5a3804c46fb..3628341440c 100644 --- a/examples/preact/shadow-dom/src/DogList.tsx +++ b/examples/preact/shadow-dom/src/DogList.tsx @@ -1,8 +1,8 @@ -import { useQuery } from '@tanstack/preact-query' +import { queryOptions, useQuery } from '@tanstack/preact-query' import { dogsQueries } from './services/dogs/queries' export const DogList = () => { - const { data, status } = useQuery(dogsQueries.list()) + const { data, status } = useQuery(queryOptions(dogsQueries.list())) if (status === 'pending') return 'Loading...' diff --git a/examples/preact/simple/src/index.tsx b/examples/preact/simple/src/index.tsx index 06a1864f6a8..4425fe86b21 100644 --- a/examples/preact/simple/src/index.tsx +++ b/examples/preact/simple/src/index.tsx @@ -1,4 +1,5 @@ import { + queryOptions, QueryClient, QueryClientProvider, useQuery, @@ -16,16 +17,18 @@ export function App() { } const Example = () => { - const { isPending, error, data, isFetching } = useQuery({ - queryKey: ['repoData'], - queryFn: async () => { - const response = await fetch( - 'https://api.github.com/repos/TanStack/query', - ) - if (!response.ok) throw new Error('Failed to fetch repo data') - return await response.json() - }, - }) + const { isPending, error, data, isFetching } = useQuery( + queryOptions({ + queryKey: ['repoData'], + queryFn: async () => { + const response = await fetch( + 'https://api.github.com/repos/TanStack/query', + ) + if (!response.ok) throw new Error('Failed to fetch repo data') + return await response.json() + }, + }), + ) if (isPending) return 'Loading...' diff --git a/examples/preact/ssr-streaming/src/App.tsx b/examples/preact/ssr-streaming/src/App.tsx index 34f2907a8f0..ef4e9850ca4 100644 --- a/examples/preact/ssr-streaming/src/App.tsx +++ b/examples/preact/ssr-streaming/src/App.tsx @@ -1,4 +1,4 @@ -import { useSuspenseQuery } from '@tanstack/preact-query' +import { useQuery, suspenseQueryOptions } from '@tanstack/preact-query' import { Suspense } from 'preact/compat' import ErrorBoundary from './ErrorBoundary' import { waitQueries } from './services/wait/queries' @@ -7,7 +7,9 @@ export const waits = [100, 200, 300, 400, 500, 600, 700] export const combinedWaits = [800, 900, 1000] function MyComponent(props: { wait: number }) { - const { data } = useSuspenseQuery(waitQueries.detail(props.wait)) + const { data } = useQuery( + suspenseQueryOptions(waitQueries.detail(props.wait)), + ) return
result: {data}
} diff --git a/examples/preact/ssr-streaming/src/entry-server.tsx b/examples/preact/ssr-streaming/src/entry-server.tsx index fd900cb4b80..3d004f9c01f 100644 --- a/examples/preact/ssr-streaming/src/entry-server.tsx +++ b/examples/preact/ssr-streaming/src/entry-server.tsx @@ -1,5 +1,11 @@ import { Transform } from 'node:stream' -import { QueryClientProvider, dehydrate, noop } from '@tanstack/preact-query' +import { + query as queryQuery, + getQueryCache, + QueryClientProvider, + dehydrate, + noop, +} from '@tanstack/preact-query' import { PreactQueryDevtools } from '@tanstack/preact-query-devtools' import { uneval } from 'devalue' import { renderToPipeableStream } from 'preact-render-to-string/stream-node' @@ -18,12 +24,12 @@ export function render(callbacks: { // Start every query the page renders up front, so a Suspense boundary // never waits for another one to finish before its own fetch starts for (const wait of [...waits, ...combinedWaits]) { - void queryClient.query(waitQueries.detail(wait)).catch(noop) + void queryQuery(queryClient, waitQueries.detail(wait)).catch(noop) } // Collect each query's state as soon as it succeeds on the server const states: Array = [] - const unsubscribe = queryClient.getQueryCache().subscribe((event) => { + const unsubscribe = getQueryCache(queryClient).subscribe((event) => { if (event.type === 'updated' && event.action.type === 'success') { states.push( dehydrate(queryClient, { diff --git a/examples/preact/ssr/src/App.tsx b/examples/preact/ssr/src/App.tsx index 47f71c2ae97..deab258d90a 100644 --- a/examples/preact/ssr/src/App.tsx +++ b/examples/preact/ssr/src/App.tsx @@ -1,4 +1,9 @@ -import { useQuery } from '@tanstack/preact-query' +import { + queryOptions, + isPending, + isError, + useQuery, +} from '@tanstack/preact-query' import { commentsQueries } from './services/comments/queries' import { postsQueries } from './services/posts/queries' import { usersQueries } from './services/users/queries' @@ -6,40 +11,40 @@ import { usersQueries } from './services/users/queries' export default function App() { // This query was prefetched on the server, so its data is already in the // server-rendered markup and is available immediately on the client - const postsQuery = useQuery(postsQueries.list()) + const postsQuery = useQuery(queryOptions(postsQueries.list())) // This query depends on the posts, and was prefetched on the server as well const authorQuery = useQuery( - usersQueries.detail(postsQuery.data?.[0]?.userId), + queryOptions(usersQueries.detail(postsQuery.data?.[0]?.userId)), ) // This query was not prefetched on the server and will not start // fetching until on the client, both patterns are fine to mix - const commentsQuery = useQuery(commentsQueries.list()) + const commentsQuery = useQuery(queryOptions(commentsQueries.list())) return (

Server Rendering with Preact Query

Comments

- {commentsQuery.isPending + {isPending(commentsQuery) ? 'Loading comments on the client...' - : commentsQuery.isError + : isError(commentsQuery) ? `Error: ${commentsQuery.error.message}` : `${commentsQuery.data.length} comments`}

Author of the first post

- {authorQuery.isPending + {isPending(authorQuery) ? 'Loading author...' - : authorQuery.isError + : isError(authorQuery) ? `Error: ${authorQuery.error.message}` : authorQuery.data.name}

Posts

- {postsQuery.isPending ? ( + {isPending(postsQuery) ? ( 'Loading posts...' - ) : postsQuery.isError ? ( + ) : isError(postsQuery) ? ( Error: {postsQuery.error.message} ) : (
    diff --git a/examples/preact/ssr/src/entry-server.tsx b/examples/preact/ssr/src/entry-server.tsx index cd15d444ecf..da4e4049722 100644 --- a/examples/preact/ssr/src/entry-server.tsx +++ b/examples/preact/ssr/src/entry-server.tsx @@ -1,4 +1,5 @@ import { + query, QueryClientProvider, dehydrate, hydrate, @@ -18,14 +19,14 @@ export async function render() { // The posts are critical content: without `.catch(noop)`, a failed fetch // throws here and the server responds with an error status - const posts = await prefetchClient.query(postsQueries.list()) + const posts = await query(prefetchClient, postsQueries.list()) // The author depends on the first post, so prefetch it once its id is known. // It's not critical: on failure it's left out of the dehydrated state and // fetched again on the client const authorId = posts[0]?.userId if (authorId) { - await prefetchClient.query(usersQueries.detail(authorId)).catch(noop) + await query(prefetchClient, usersQueries.detail(authorId)).catch(noop) } const dehydratedState = dehydrate(prefetchClient) diff --git a/examples/preact/star-wars-preact-iso/src/Character.tsx b/examples/preact/star-wars-preact-iso/src/Character.tsx index 75e19895c92..1d3111cb9aa 100644 --- a/examples/preact/star-wars-preact-iso/src/Character.tsx +++ b/examples/preact/star-wars-preact-iso/src/Character.tsx @@ -1,4 +1,4 @@ -import { useQuery } from '@tanstack/preact-query' +import { queryOptions, useQuery } from '@tanstack/preact-query' import { useRoute } from 'preact-iso' import { charactersQueries } from './services/characters/queries' import { filmsQueries } from './services/films/queries' @@ -8,7 +8,9 @@ export default function Character() { const { params } = useRoute() const characterId = params.characterId - const { status, data } = useQuery(charactersQueries.detail(characterId)) + const { status, data } = useQuery( + queryOptions(charactersQueries.detail(characterId)), + ) if (status === 'pending') return

    Loading...

    if (status === 'error') return

    Error :(

    @@ -49,7 +51,7 @@ export default function Character() { } function Film({ filmId }: { filmId: string }) { - const { data, status } = useQuery(filmsQueries.detail(filmId)) + const { data, status } = useQuery(queryOptions(filmsQueries.detail(filmId))) if (status === 'success') { return ( @@ -63,7 +65,9 @@ function Film({ filmId }: { filmId: string }) { } function Homeworld({ homeworldId }: { homeworldId: string }) { - const { data, status } = useQuery(planetsQueries.detail(homeworldId)) + const { data, status } = useQuery( + queryOptions(planetsQueries.detail(homeworldId)), + ) if (status === 'pending') return Loading... if (status === 'error') return Error :( diff --git a/examples/preact/star-wars-preact-iso/src/Characters.tsx b/examples/preact/star-wars-preact-iso/src/Characters.tsx index caf8b13005a..5d108bf05f2 100644 --- a/examples/preact/star-wars-preact-iso/src/Characters.tsx +++ b/examples/preact/star-wars-preact-iso/src/Characters.tsx @@ -1,8 +1,8 @@ -import { useQuery } from '@tanstack/preact-query' +import { queryOptions, useQuery } from '@tanstack/preact-query' import { charactersQueries } from './services/characters/queries' export default function Characters() { - const { status, data } = useQuery(charactersQueries.list()) + const { status, data } = useQuery(queryOptions(charactersQueries.list())) if (status === 'pending') return

    Loading...

    if (status === 'error') return

    Error :(

    diff --git a/examples/preact/star-wars-preact-iso/src/Film.tsx b/examples/preact/star-wars-preact-iso/src/Film.tsx index 271bcc5634b..dd221e7f0fe 100644 --- a/examples/preact/star-wars-preact-iso/src/Film.tsx +++ b/examples/preact/star-wars-preact-iso/src/Film.tsx @@ -1,4 +1,4 @@ -import { useQuery } from '@tanstack/preact-query' +import { queryOptions, useQuery } from '@tanstack/preact-query' import { useRoute } from 'preact-iso' import { charactersQueries } from './services/characters/queries' import { filmsQueries } from './services/films/queries' @@ -6,7 +6,7 @@ import { filmsQueries } from './services/films/queries' export default function Film() { const { filmId } = useRoute().params - const { data, status } = useQuery(filmsQueries.detail(filmId)) + const { data, status } = useQuery(queryOptions(filmsQueries.detail(filmId))) if (!filmId) { return

    Invalid film ID

    @@ -32,7 +32,9 @@ export default function Film() { } function Character({ characterId }: { characterId: string }) { - const { data, status } = useQuery(charactersQueries.detail(characterId)) + const { data, status } = useQuery( + queryOptions(charactersQueries.detail(characterId)), + ) if (status !== 'success') { return null diff --git a/examples/preact/star-wars-preact-iso/src/Films.tsx b/examples/preact/star-wars-preact-iso/src/Films.tsx index 1cf8c88a53e..41252ee69ab 100644 --- a/examples/preact/star-wars-preact-iso/src/Films.tsx +++ b/examples/preact/star-wars-preact-iso/src/Films.tsx @@ -1,8 +1,8 @@ -import { useQuery } from '@tanstack/preact-query' +import { queryOptions, useQuery } from '@tanstack/preact-query' import { filmsQueries } from './services/films/queries' export default function Films() { - const { data, status } = useQuery(filmsQueries.list()) + const { data, status } = useQuery(queryOptions(filmsQueries.list())) if (status === 'pending') { return

    Loading...

    diff --git a/examples/preact/suspense/src/components/Project.tsx b/examples/preact/suspense/src/components/Project.tsx index 696132dbb2f..045278c6c9b 100644 --- a/examples/preact/suspense/src/components/Project.tsx +++ b/examples/preact/suspense/src/components/Project.tsx @@ -1,4 +1,4 @@ -import { useSuspenseQuery } from '@tanstack/preact-query' +import { useQuery, suspenseQueryOptions } from '@tanstack/preact-query' import { projectsQueries } from '../services/projects/queries' import Button from './Button' import Spinner from './Spinner' @@ -10,8 +10,8 @@ export default function Project({ activeProject: string setActiveProject: (activeProject: string | null) => void }) { - const { data, isFetching } = useSuspenseQuery( - projectsQueries.detail(activeProject), + const { data, isFetching } = useQuery( + suspenseQueryOptions(projectsQueries.detail(activeProject)), ) return ( diff --git a/examples/preact/suspense/src/components/Projects.tsx b/examples/preact/suspense/src/components/Projects.tsx index 8d21306286f..797e1353f99 100644 --- a/examples/preact/suspense/src/components/Projects.tsx +++ b/examples/preact/suspense/src/components/Projects.tsx @@ -1,4 +1,10 @@ -import { noop, useQueryClient, useSuspenseQuery } from '@tanstack/preact-query' +import { + useQuery, + suspenseQueryOptions, + query, + noop, + useQueryClient, +} from '@tanstack/preact-query' import { projectsQueries } from '../services/projects/queries' import Button from './Button' import Spinner from './Spinner' @@ -9,7 +15,9 @@ export default function Projects({ setActiveProject: (activeProject: string | null) => void }) { const queryClient = useQueryClient() - const { data, isFetching } = useSuspenseQuery(projectsQueries.list()) + const { data, isFetching } = useQuery( + suspenseQueryOptions(projectsQueries.list()), + ) return (
    @@ -19,9 +27,10 @@ export default function Projects({ )} - {isFetchingNextPage && ( + {fetchingNextPage && (
    Fetching next page...
    )}
    diff --git a/examples/react/algolia/src/services/products/queries.ts b/examples/react/algolia/src/services/products/queries.ts index 30423a156d8..71158f00c4f 100644 --- a/examples/react/algolia/src/services/products/queries.ts +++ b/examples/react/algolia/src/services/products/queries.ts @@ -1,4 +1,4 @@ -import { infiniteQueryOptions, skipToken } from '@tanstack/react-query' +import { infiniteQueryOptions, select, skipToken } from '@tanstack/react-query' import { productsAPI } from './api' import type { SearchOptions } from './types' @@ -26,6 +26,9 @@ export const productsQueries = { hitsPerPage, }) : skipToken, + select: [select, (data) => data.pages.flatMap((page) => page.hits)], + staleTime: 30 * 1000, + gcTime: 15 * 60 * 1000, initialPageParam: 0, getNextPageParam: (lastPage, _allPages, lastPageParam) => lastPageParam + 1 < lastPage.nbPages ? lastPageParam + 1 : undefined, diff --git a/examples/react/auto-refetching-nextjs-pages-router/README.md b/examples/react/auto-refetching-nextjs-pages-router/README.md index 12e22d7856c..ddba31245ef 100644 --- a/examples/react/auto-refetching-nextjs-pages-router/README.md +++ b/examples/react/auto-refetching-nextjs-pages-router/README.md @@ -7,8 +7,8 @@ Built with [Next.js (Pages Router)](https://nextjs.org/docs/pages). ## How it works - `src/services/todos/queries.ts` defines `todosQueries.list()` with `queryOptions`, and `todosMutations.create()` and `todosMutations.deleteAll()` with `mutationOptions`. -- `src/pages/index.tsx` passes `todosQueries.list()` to `useQuery` with `refetchInterval: intervalMs`. The interval can be changed in a number input, and a dot lights up while `isFetching` is `true`. -- In `src/pages/index.tsx`, both mutations run through `useMutation` and call `queryClient.invalidateQueries({ queryKey: todosQueries.all() })` in `onSuccess`, so the list refetches after adding a todo or clearing the list. +- `src/pages/index.tsx` passes `todosQueries.list()` to `useQuery` with `refetchInterval: refetchInterval(intervalMs)`. The interval can be changed in a number input, and a dot lights up while `isFetching` is `true`. +- In `src/pages/index.tsx`, both mutations run through `useMutation` and call `invalidateQueries(queryClient, { queryKey: todosQueries.all() })` in `onSuccess`, so the list refetches after adding a todo or clearing the list. - `src/pages/api/data.ts` is a Next.js API route that keeps the list in memory, adds an item with `?add=`, empties it with `?clear=1`, and responds after a 100 ms delay. To run this example: diff --git a/examples/react/auto-refetching-nextjs-pages-router/src/pages/index.tsx b/examples/react/auto-refetching-nextjs-pages-router/src/pages/index.tsx index 615043fa4fe..3cede56b514 100644 --- a/examples/react/auto-refetching-nextjs-pages-router/src/pages/index.tsx +++ b/examples/react/auto-refetching-nextjs-pages-router/src/pages/index.tsx @@ -1,4 +1,12 @@ -import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { + invalidateQueries, + isFetching, + queryOptions, + refetchInterval, + useMutation, + useQuery, + useQueryClient, +} from '@tanstack/react-query' import { ReactQueryDevtools } from '@tanstack/react-query-devtools' import React from 'react' import { todosMutations, todosQueries } from '../services/todos/queries' @@ -8,22 +16,26 @@ export default function Example() { const [intervalMs, setIntervalMs] = React.useState(1000) const [value, setValue] = React.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 { status, data, error } = queryResult + const fetching = isFetching(queryResult) 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...

    @@ -51,8 +63,8 @@ export default function Example() { marginLeft: '.5rem', width: 10, height: 10, - background: isFetching ? 'green' : 'transparent', - transition: !isFetching ? 'all .3s ease' : 'none', + background: fetching ? 'green' : 'transparent', + transition: !fetching ? 'all .3s ease' : 'none', borderRadius: '100%', transform: 'scale(2)', }} diff --git a/examples/react/basic-graphql-request/README.md b/examples/react/basic-graphql-request/README.md index 4c29fca5884..fa21700c7ae 100644 --- a/examples/react/basic-graphql-request/README.md +++ b/examples/react/basic-graphql-request/README.md @@ -7,7 +7,7 @@ The basic posts example, fetching from a GraphQL API with `graphql-request`. - `src/services/posts/queries.ts` defines `postsQueries.list()` and `postsQueries.detail(postId)` with `queryOptions`, keyed under `['posts']`. - `src/services/posts/api.ts` sends GraphQL queries to GraphQLZero with `request` and `gql` from `graphql-request`, selecting only `id` and `title` for the list. - `src/index.tsx` renders `Posts` with `useQuery(postsQueries.list())` and `Post` with `useQuery(postsQueries.detail(postId))`. Both show "Background Updating..." while `isFetching` is `true`. -- In `src/index.tsx`, the list marks a post as visited when `queryClient.getQueryData(postsQueries.detail(post.id).queryKey)` returns cached data. +- In `src/index.tsx`, the list marks a post as visited when `getQueryData(queryClient, postsQueries.detail(post.id).queryKey)` returns cached data. To run this example: diff --git a/examples/react/basic-graphql-request/src/index.tsx b/examples/react/basic-graphql-request/src/index.tsx index 4573bb97be4..83ec1137977 100644 --- a/examples/react/basic-graphql-request/src/index.tsx +++ b/examples/react/basic-graphql-request/src/index.tsx @@ -1,6 +1,8 @@ import { QueryClient, QueryClientProvider, + getQueryData, + isFetching, useQuery, useQueryClient, } from '@tanstack/react-query' @@ -42,7 +44,9 @@ function Posts({ setPostId: React.Dispatch> }) { const queryClient = useQueryClient() - const { status, data, error, isFetching } = useQuery(postsQueries.list()) + const queryResult = useQuery(postsQueries.list()) + const { status, data, error } = queryResult + const fetching = isFetching(queryResult) return (
    @@ -63,7 +67,8 @@ function Posts({ style={ // We can find the existing query data here to show bold links for // ones that are cached - queryClient.getQueryData( + getQueryData( + queryClient, postsQueries.detail(post.id).queryKey, ) ? { @@ -78,7 +83,7 @@ function Posts({

    ))}
    -
    {isFetching ? 'Background Updating...' : ' '}
    +
    {fetching ? 'Background Updating...' : ' '}
    )}
@@ -93,9 +98,9 @@ function Post({ postId: string setPostId: React.Dispatch> }) { - const { status, data, error, isFetching } = useQuery( - postsQueries.detail(postId), - ) + const queryResult = useQuery(postsQueries.detail(postId)) + const { status, data, error } = queryResult + const fetching = isFetching(queryResult) return (
@@ -114,7 +119,7 @@ function Post({

{data.body}

-
{isFetching ? 'Background Updating...' : ' '}
+
{fetching ? 'Background Updating...' : ' '}
)}
diff --git a/examples/react/basic/README.md b/examples/react/basic/README.md index a6bd9249e4a..45cf19ef1ba 100644 --- a/examples/react/basic/README.md +++ b/examples/react/basic/README.md @@ -6,7 +6,7 @@ A list of posts and a post detail view. Posts you have already opened are marked - `src/services/posts/queries.ts` defines `postsQueries.list()` and `postsQueries.detail(id)` with `queryOptions`, keyed under `['posts']`. `src/services/posts/api.ts` fetches the posts from JSONPlaceholder. - `src/index.tsx` renders `Posts` with `useQuery(postsQueries.list())` and `Post` with `useQuery(postsQueries.detail(postId))`. Both show "Background Updating..." while `isFetching` is `true`. -- In `src/index.tsx`, the list marks a post as visited when `queryClient.getQueryData(postsQueries.detail(post.id).queryKey)` returns cached data. +- In `src/index.tsx`, the list marks a post as visited when `getQueryData(queryClient, postsQueries.detail(post.id).queryKey)` returns cached data. - `src/index.tsx` wraps the app in `PersistQueryClientProvider` with a `createAsyncStoragePersister` over `window.localStorage`, and its `QueryClient` sets `gcTime` to 24 hours so the persisted queries are kept. To run this example: diff --git a/examples/react/basic/src/index.tsx b/examples/react/basic/src/index.tsx index d1fddde2de3..402618d24eb 100644 --- a/examples/react/basic/src/index.tsx +++ b/examples/react/basic/src/index.tsx @@ -1,5 +1,11 @@ import { createAsyncStoragePersister } from '@tanstack/query-async-storage-persister' -import { QueryClient, useQuery, useQueryClient } from '@tanstack/react-query' +import { + QueryClient, + getQueryData, + isFetching, + useQuery, + useQueryClient, +} from '@tanstack/react-query' import { ReactQueryDevtools } from '@tanstack/react-query-devtools' import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client' import * as React from 'react' @@ -24,7 +30,9 @@ function Posts({ setPostId: React.Dispatch> }) { const queryClient = useQueryClient() - const { status, data, error, isFetching } = useQuery(postsQueries.list()) + const queryResult = useQuery(postsQueries.list()) + const { status, data, error } = queryResult + const fetching = isFetching(queryResult) return (
@@ -45,7 +53,8 @@ function Posts({ style={ // We can access the query data here to show bold links for // ones that are cached - queryClient.getQueryData( + getQueryData( + queryClient, postsQueries.detail(post.id).queryKey, ) ? { @@ -60,7 +69,7 @@ function Posts({

))}
-
{isFetching ? 'Background Updating...' : ' '}
+
{fetching ? 'Background Updating...' : ' '}
)}
@@ -75,9 +84,9 @@ function Post({ postId: number setPostId: React.Dispatch> }) { - const { status, data, error, isFetching } = useQuery( - postsQueries.detail(postId), - ) + const queryResult = useQuery(postsQueries.detail(postId)) + const { status, data, error } = queryResult + const fetching = isFetching(queryResult) return (
@@ -96,7 +105,7 @@ function Post({

{data.body}

-
{isFetching ? 'Background Updating...' : ' '}
+
{fetching ? 'Background Updating...' : ' '}
)}
diff --git a/examples/react/chat/src/index.tsx b/examples/react/chat/src/index.tsx index 2cf75901fc3..d0d818c8c94 100644 --- a/examples/react/chat/src/index.tsx +++ b/examples/react/chat/src/index.tsx @@ -1,6 +1,7 @@ import { QueryClient, QueryClientProvider, + isFetching, useQuery, } from '@tanstack/react-query' import { ReactQueryDevtools } from '@tanstack/react-query-devtools' @@ -22,11 +23,9 @@ 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)) + const { error, data = [] } = queryResult + const fetching = isFetching(queryResult) if (error) return 'An error has occurred: ' + error.message @@ -34,7 +33,7 @@ function ChatMessage({ id, question }: { id: string; question: string }) {
diff --git a/examples/react/contacts-react-router/README.md b/examples/react/contacts-react-router/README.md index 4b173b33d9d..4162e6b872d 100644 --- a/examples/react/contacts-react-router/README.md +++ b/examples/react/contacts-react-router/README.md @@ -6,10 +6,10 @@ Built with [React Router](https://reactrouter.com). ## How it works -- `src/services/contacts/queries.ts` defines `contactsQueries.list(q)` and `contactsQueries.detail(id)` with `queryOptions`, keyed under `['contacts', 'list']` and `['contacts', 'detail']`. The detail `queryFn` throws a 404 `Response` when the contact does not exist. `src/services/contacts/api.ts` stores the contacts in `localStorage` behind a random delay. -- The loaders in `src/routes/root.tsx` and `src/routes/contact.tsx` await `queryClient.query({ ...options, staleTime: 'static' })`, which uses cached data when it exists and fetches only on a cache miss. The route components then read the same options with `useSuspenseQuery`, After the 10-second `staleTime` set on the `QueryClient` in `src/index.tsx`, the data is stale, and `useSuspenseQuery` refetches it in the background on the next trigger, such as a component mount or window focus. +- `src/services/contacts/queries.ts` defines `contactsQueries.list(q)` and `contactsQueries.detail(id)` with `suspenseQueryOptions`, keyed under `['contacts', 'list']` and `['contacts', 'detail']`. The detail `queryFn` throws a 404 `Response` when the contact does not exist. `src/services/contacts/api.ts` stores the contacts in `localStorage` behind a random delay. +- The loaders in `src/routes/root.tsx` and `src/routes/contact.tsx` await `query(queryClient, { ...options, staleTime: 'static' })`, which uses cached data when it exists and fetches only on a cache miss. The route components then read the same options with `useQuery` and `suspenseQueryOptions`. After the 10-second `staleTime` set on the `QueryClient` in `src/index.tsx`, the data is stale, and `useQuery` with `suspenseQueryOptions` refetches it in the background on the next trigger, such as a component mount or window focus. - `src/routes/root.tsx` debounces the search input with `useDebouncedCallback` from TanStack Pacer and shows a spinner while `useIsFetching({ queryKey: contactsQueries.lists() })` is greater than 0. -- The route actions in `src/routes/new.tsx`, `src/routes/edit.tsx`, `src/routes/contact.tsx`, and `src/routes/destroy.tsx` call the API, then `queryClient.invalidateQueries` so the list and detail refetch. +- The route actions in `src/routes/new.tsx`, `src/routes/edit.tsx`, `src/routes/contact.tsx`, and `src/routes/destroy.tsx` call the API, then `invalidateQueries` so the list and detail refetch. To run this example: diff --git a/examples/react/contacts-react-router/src/routes/contact.tsx b/examples/react/contacts-react-router/src/routes/contact.tsx index 889b7f69fb9..abdad5b0f38 100644 --- a/examples/react/contacts-react-router/src/routes/contact.tsx +++ b/examples/react/contacts-react-router/src/routes/contact.tsx @@ -1,4 +1,4 @@ -import { useSuspenseQuery } from '@tanstack/react-query' +import { invalidateQueries, query, useQuery } from '@tanstack/react-query' import { Form, Link, useFetcher, useLoaderData } from 'react-router' import { contactsAPI } from '../services/contacts/api' import { contactsQueries } from '../services/contacts/queries' @@ -12,7 +12,7 @@ export const loader = if (!params.contactId) { throw new Error('No contact ID provided') } - await queryClient.query({ + await query(queryClient, { ...contactsQueries.detail(params.contactId), staleTime: 'static', }) @@ -29,13 +29,13 @@ export const action = await contactsAPI.updateContact(params.contactId, { favorite: formData.get('favorite') === 'true', }) - await queryClient.invalidateQueries({ queryKey: contactsQueries.all() }) + await invalidateQueries(queryClient, { queryKey: contactsQueries.all() }) return null } export default function Contact() { const { contactId } = useLoaderData>() - const { data: contact } = useSuspenseQuery(contactsQueries.detail(contactId)) + const { data: contact } = useQuery(contactsQueries.detail(contactId)) return (
diff --git a/examples/react/contacts-react-router/src/routes/destroy.tsx b/examples/react/contacts-react-router/src/routes/destroy.tsx index 2c39d85c93c..1dfe73ad66b 100644 --- a/examples/react/contacts-react-router/src/routes/destroy.tsx +++ b/examples/react/contacts-react-router/src/routes/destroy.tsx @@ -1,3 +1,4 @@ +import { invalidateQueries } from '@tanstack/react-query' import { redirect } from 'react-router' import { contactsAPI } from '../services/contacts/api' import { contactsQueries } from '../services/contacts/queries' @@ -11,6 +12,6 @@ export const action = throw new Error('No contact ID provided') } await contactsAPI.deleteContact(params.contactId) - queryClient.invalidateQueries({ queryKey: contactsQueries.all() }) + invalidateQueries(queryClient, { queryKey: contactsQueries.all() }) return redirect('/') } diff --git a/examples/react/contacts-react-router/src/routes/edit.tsx b/examples/react/contacts-react-router/src/routes/edit.tsx index 7ab54d9ab60..1f00775d64d 100644 --- a/examples/react/contacts-react-router/src/routes/edit.tsx +++ b/examples/react/contacts-react-router/src/routes/edit.tsx @@ -1,4 +1,4 @@ -import { useSuspenseQuery } from '@tanstack/react-query' +import { invalidateQueries, useQuery } from '@tanstack/react-query' import { Form, redirect, useLoaderData, useNavigate } from 'react-router' import { contactsAPI } from '../services/contacts/api' import { contactsQueries } from '../services/contacts/queries' @@ -16,13 +16,13 @@ export const action = throw new Error('No contact ID provided') } await contactsAPI.updateContact(params.contactId, updates) - queryClient.invalidateQueries({ queryKey: contactsQueries.all() }) + invalidateQueries(queryClient, { queryKey: contactsQueries.all() }) return redirect(`/contacts/${params.contactId}`) } export default function Edit() { const { contactId } = useLoaderData>() - const { data: contact } = useSuspenseQuery(contactsQueries.detail(contactId)) + const { data: contact } = useQuery(contactsQueries.detail(contactId)) return } diff --git a/examples/react/contacts-react-router/src/routes/new.tsx b/examples/react/contacts-react-router/src/routes/new.tsx index 39660139d27..b3db88902d6 100644 --- a/examples/react/contacts-react-router/src/routes/new.tsx +++ b/examples/react/contacts-react-router/src/routes/new.tsx @@ -1,3 +1,4 @@ +import { invalidateQueries } from '@tanstack/react-query' import { redirect } from 'react-router' import { contactsAPI } from '../services/contacts/api' import { contactsQueries } from '../services/contacts/queries' @@ -11,7 +12,7 @@ export const action = const formData = await request.formData() const data = Object.fromEntries(formData) const contact = await contactsAPI.createContact(data as any) - queryClient.invalidateQueries({ queryKey: contactsQueries.lists() }) + invalidateQueries(queryClient, { queryKey: contactsQueries.lists() }) return redirect(`/contacts/${contact.id}`) } diff --git a/examples/react/contacts-react-router/src/routes/root.tsx b/examples/react/contacts-react-router/src/routes/root.tsx index e1cb9d92b37..2998b50f3d4 100644 --- a/examples/react/contacts-react-router/src/routes/root.tsx +++ b/examples/react/contacts-react-router/src/routes/root.tsx @@ -1,5 +1,5 @@ import { useDebouncedCallback } from '@tanstack/react-pacer/debouncer' -import { useIsFetching, useSuspenseQuery } from '@tanstack/react-query' +import { query, useIsFetching, useQuery } from '@tanstack/react-query' import { Link, NavLink, @@ -17,13 +17,16 @@ export const loader = async ({ request }: LoaderFunctionArgs) => { const url = new URL(request.url) const q = url.searchParams.get('q') ?? '' - await queryClient.query({ ...contactsQueries.list(q), staleTime: 'static' }) + await query(queryClient, { + ...contactsQueries.list(q), + staleTime: 'static', + }) return { q } } export default function Root() { const { q } = useLoaderData>() - const { data: contacts } = useSuspenseQuery(contactsQueries.list(q)) + const { data: contacts } = useQuery(contactsQueries.list(q)) const searching = useIsFetching({ queryKey: contactsQueries.lists() }) > 0 const navigation = useNavigation() const submit = useSubmit() diff --git a/examples/react/contacts-react-router/src/services/contacts/queries.ts b/examples/react/contacts-react-router/src/services/contacts/queries.ts index 6dddaf37585..cab86e4e119 100644 --- a/examples/react/contacts-react-router/src/services/contacts/queries.ts +++ b/examples/react/contacts-react-router/src/services/contacts/queries.ts @@ -1,16 +1,16 @@ -import { queryOptions } from '@tanstack/react-query' +import { suspenseQueryOptions } from '@tanstack/react-query' import { contactsAPI } from './api' export const contactsQueries = { all: () => ['contacts'] as const, lists: () => [...contactsQueries.all(), 'list'] as const, list: (q?: string) => - queryOptions({ + suspenseQueryOptions({ queryKey: [...contactsQueries.lists(), { q }] as const, queryFn: () => contactsAPI.getContacts(q), }), detail: (id: string) => - queryOptions({ + suspenseQueryOptions({ queryKey: [...contactsQueries.all(), 'detail', id] as const, queryFn: async () => { const contact = await contactsAPI.getContact(id) diff --git a/examples/react/contacts-tanstack-router/README.md b/examples/react/contacts-tanstack-router/README.md index a9e33b003d1..72957113f85 100644 --- a/examples/react/contacts-tanstack-router/README.md +++ b/examples/react/contacts-tanstack-router/README.md @@ -6,11 +6,11 @@ Built with [TanStack Router](https://tanstack.com/router). ## How it works -- `src/services/contacts/queries.ts` defines `contactsQueries.list(q)` and `contactsQueries.detail(id)` with `queryOptions`, and `contactsMutations.create()`, `update()`, and `delete()` with `mutationOptions`. The detail `queryFn` throws TanStack Router's `notFound()` when the contact does not exist. `src/services/contacts/api.ts` stores the contacts in `localStorage` behind a random delay. -- The loaders in `src/routes/__root.tsx` (with `loaderDeps` on the `q` search param) and `src/routes/contacts.$contactId.route.tsx` call `queryClient.query({ ...options, staleTime: 'static' })` with the `queryClient` from the router context, which uses cached data when it exists and fetches only on a cache miss. Components read the same options with `useSuspenseQuery`, After the 10-second `staleTime` set in `src/index.tsx`, the data is stale, and `useSuspenseQuery` refetches it in the background on the next trigger, such as a component mount or window focus. +- `src/services/contacts/queries.ts` defines `contactsQueries.list(q)` and `contactsQueries.detail(id)` with `suspenseQueryOptions`, and `contactsMutations.create()`, `update()`, and `delete()` with `mutationOptions`. The detail `queryFn` throws TanStack Router's `notFound()` when the contact does not exist. `src/services/contacts/api.ts` stores the contacts in `localStorage` behind a random delay. +- The loaders in `src/routes/__root.tsx` (with `loaderDeps` on the `q` search param) and `src/routes/contacts.$contactId.route.tsx` call `query(queryClient, { ...options, staleTime: 'static' })` with the `queryClient` from the router context, which uses cached data when it exists and fetches only on a cache miss. Components read the same options with `useQuery` and `suspenseQueryOptions`. After the 10-second `staleTime` set in `src/index.tsx`, the data is stale, and `useQuery` with `suspenseQueryOptions` refetches it in the background on the next trigger, such as a component mount or window focus. - `src/index.tsx` creates the router with `defaultPreload: 'intent'`, so hovering a contact link runs its loader ahead of time. - `src/routes/__root.tsx` debounces the search input with `useDebouncedCallback` from TanStack Pacer and shows a spinner while `useIsFetching({ queryKey: contactsQueries.lists() })` is greater than 0. -- `src/routes/contacts.new.tsx`, `src/routes/contacts.$contactId.edit.tsx`, and `src/routes/contacts.$contactId.index.tsx` run the mutations with `useMutation` and call `queryClient.invalidateQueries` afterward. The favorite button shows the pending value from `updateContact.variables` while the mutation `isPending`. +- `src/routes/contacts.new.tsx`, `src/routes/contacts.$contactId.edit.tsx`, and `src/routes/contacts.$contactId.index.tsx` run the mutations with `useMutation` and call `invalidateQueries` afterward. The favorite button shows the pending value from `updateContact.variables` while the mutation `isPending`. To run this example: diff --git a/examples/react/contacts-tanstack-router/src/routes/__root.tsx b/examples/react/contacts-tanstack-router/src/routes/__root.tsx index 86140efd1f2..74607db7593 100644 --- a/examples/react/contacts-tanstack-router/src/routes/__root.tsx +++ b/examples/react/contacts-tanstack-router/src/routes/__root.tsx @@ -1,5 +1,5 @@ import { useDebouncedCallback } from '@tanstack/react-pacer/debouncer' -import { useIsFetching, useSuspenseQuery } from '@tanstack/react-query' +import { query, useIsFetching, useQuery } from '@tanstack/react-query' import { Link, Outlet, @@ -18,14 +18,14 @@ export const Route = createRootRouteWithContext<{ queryClient: QueryClient }>()( }), loaderDeps: ({ search: { q } }) => ({ q }), loader: ({ context: { queryClient }, deps: { q } }) => - queryClient.query({ ...contactsQueries.list(q), staleTime: 'static' }), + query(queryClient, { ...contactsQueries.list(q), staleTime: 'static' }), component: Root, }, ) function Root() { const { q } = Route.useSearch() - const { data: contacts } = useSuspenseQuery(contactsQueries.list(q)) + const { data: contacts } = useQuery(contactsQueries.list(q)) const searching = useIsFetching({ queryKey: contactsQueries.lists() }) > 0 const loading = useRouterState({ select: (state) => state.isLoading }) const navigate = useNavigate() diff --git a/examples/react/contacts-tanstack-router/src/routes/contacts.$contactId.edit.tsx b/examples/react/contacts-tanstack-router/src/routes/contacts.$contactId.edit.tsx index b3a68d65ef1..97d8f24fca3 100644 --- a/examples/react/contacts-tanstack-router/src/routes/contacts.$contactId.edit.tsx +++ b/examples/react/contacts-tanstack-router/src/routes/contacts.$contactId.edit.tsx @@ -1,7 +1,8 @@ import { + invalidateQueries, useMutation, + useQuery, useQueryClient, - useSuspenseQuery, } from '@tanstack/react-query' import { createFileRoute, useNavigate } from '@tanstack/react-router' import ContactForm from '../contact-form' @@ -17,13 +18,13 @@ export const Route = createFileRoute('/contacts/$contactId/edit')({ function Edit() { const { contactId } = Route.useParams() const { q } = Route.useSearch() - const { data: contact } = useSuspenseQuery(contactsQueries.detail(contactId)) + const { data: contact } = useQuery(contactsQueries.detail(contactId)) const queryClient = useQueryClient() const navigate = useNavigate() const updateContact = useMutation({ ...contactsMutations.update(), onSuccess: async () => { - await queryClient.invalidateQueries({ queryKey: contactsQueries.all() }) + await invalidateQueries(queryClient, { queryKey: contactsQueries.all() }) await navigate({ to: '/contacts/$contactId', params: { contactId }, diff --git a/examples/react/contacts-tanstack-router/src/routes/contacts.$contactId.index.tsx b/examples/react/contacts-tanstack-router/src/routes/contacts.$contactId.index.tsx index a84757571b0..c93860b23f4 100644 --- a/examples/react/contacts-tanstack-router/src/routes/contacts.$contactId.index.tsx +++ b/examples/react/contacts-tanstack-router/src/routes/contacts.$contactId.index.tsx @@ -1,7 +1,8 @@ import { + invalidateQueries, useMutation, + useQuery, useQueryClient, - useSuspenseQuery, } from '@tanstack/react-query' import { Link, createFileRoute, useNavigate } from '@tanstack/react-router' import { @@ -17,14 +18,14 @@ export const Route = createFileRoute('/contacts/$contactId/')({ function ContactPage() { const { contactId } = Route.useParams() const { q } = Route.useSearch() - const { data: contact } = useSuspenseQuery(contactsQueries.detail(contactId)) + const { data: contact } = useQuery(contactsQueries.detail(contactId)) const queryClient = useQueryClient() const navigate = useNavigate() const deleteContact = useMutation({ ...contactsMutations.delete(), onSuccess: async () => { await navigate({ to: '/', search: { q } }) - await queryClient.invalidateQueries({ queryKey: contactsQueries.all() }) + await invalidateQueries(queryClient, { queryKey: contactsQueries.all() }) }, }) @@ -87,7 +88,7 @@ function Favorite({ contact }: { contact: Contact }) { const updateContact = useMutation({ ...contactsMutations.update(), onSettled: () => - queryClient.invalidateQueries({ queryKey: contactsQueries.all() }), + invalidateQueries(queryClient, { queryKey: contactsQueries.all() }), }) const favorite = updateContact.isPending ? Boolean(updateContact.variables.updates.favorite) diff --git a/examples/react/contacts-tanstack-router/src/routes/contacts.$contactId.route.tsx b/examples/react/contacts-tanstack-router/src/routes/contacts.$contactId.route.tsx index dd13a1d7fd3..664509ece05 100644 --- a/examples/react/contacts-tanstack-router/src/routes/contacts.$contactId.route.tsx +++ b/examples/react/contacts-tanstack-router/src/routes/contacts.$contactId.route.tsx @@ -1,9 +1,10 @@ +import { query } from '@tanstack/react-query' import { createFileRoute } from '@tanstack/react-router' import { contactsQueries } from '../services/contacts/queries' export const Route = createFileRoute('/contacts/$contactId')({ loader: ({ context: { queryClient }, params: { contactId } }) => - queryClient.query({ + query(queryClient, { ...contactsQueries.detail(contactId), staleTime: 'static', }), diff --git a/examples/react/contacts-tanstack-router/src/routes/contacts.new.tsx b/examples/react/contacts-tanstack-router/src/routes/contacts.new.tsx index 40e5ff6f18a..6d653861184 100644 --- a/examples/react/contacts-tanstack-router/src/routes/contacts.new.tsx +++ b/examples/react/contacts-tanstack-router/src/routes/contacts.new.tsx @@ -1,4 +1,8 @@ -import { useMutation, useQueryClient } from '@tanstack/react-query' +import { + invalidateQueries, + useMutation, + useQueryClient, +} from '@tanstack/react-query' import { createFileRoute, useNavigate } from '@tanstack/react-router' import ContactForm from '../contact-form' import { @@ -17,7 +21,7 @@ function New() { const createContact = useMutation({ ...contactsMutations.create(), onSuccess: async (contact) => { - await queryClient.invalidateQueries({ + await invalidateQueries(queryClient, { queryKey: contactsQueries.lists(), }) await navigate({ diff --git a/examples/react/contacts-tanstack-router/src/services/contacts/queries.ts b/examples/react/contacts-tanstack-router/src/services/contacts/queries.ts index 47ac1ce47af..4710c41c15a 100644 --- a/examples/react/contacts-tanstack-router/src/services/contacts/queries.ts +++ b/examples/react/contacts-tanstack-router/src/services/contacts/queries.ts @@ -1,4 +1,4 @@ -import { mutationOptions, queryOptions } from '@tanstack/react-query' +import { mutationOptions, suspenseQueryOptions } from '@tanstack/react-query' import { notFound } from '@tanstack/react-router' import { contactsAPI } from './api' import type { Contact } from './types' @@ -7,12 +7,12 @@ export const contactsQueries = { all: () => ['contacts'] as const, lists: () => [...contactsQueries.all(), 'list'] as const, list: (q?: string) => - queryOptions({ + suspenseQueryOptions({ queryKey: [...contactsQueries.lists(), { q }] as const, queryFn: () => contactsAPI.getContacts(q), }), detail: (id: string) => - queryOptions({ + suspenseQueryOptions({ queryKey: [...contactsQueries.all(), 'detail', id] as const, queryFn: async () => { const contact = await contactsAPI.getContact(id) diff --git a/examples/react/default-query-function/README.md b/examples/react/default-query-function/README.md index 9692b6544b0..8a17e2a79c1 100644 --- a/examples/react/default-query-function/README.md +++ b/examples/react/default-query-function/README.md @@ -1,12 +1,12 @@ # TanStack React Query Default Query Function Example -Sets a default `queryFn` on the `QueryClient` that builds the request URL from the query key, so each query only passes a `queryKey`. +Sets a default `queryFn` on the `QueryClient` that builds the request URL from the query key, so each query can reuse the same fetcher. ## How it works -- `src/index.tsx` defines `defaultQueryFn`, which fetches `https://jsonplaceholder.typicode.com${queryKey[0]}`, and registers it as `defaultOptions.queries.queryFn` on the `QueryClient`. -- In `src/index.tsx`, `Posts` calls `useQuery>({ queryKey: ['/posts'] })` and `Post` calls ``useQuery({ queryKey: [`/posts/${postId}`], enabled: !!postId })``, without a `queryFn`. -- In `src/index.tsx`, the list marks a post as visited when ``queryClient.getQueryData([`/posts/${post.id}`])`` returns cached data. +- `src/index.tsx` defines `fetchByQueryKey`, which fetches `https://jsonplaceholder.typicode.com${queryKey[0]}`, and registers it as `defaultOptions.queries.queryFn` on the `QueryClient`. +- In `src/index.tsx`, `Posts` and `Post` pass `queryOptions` to `useQuery`. Both specify `queryFn: defaultQueryFn` to use the function configured on the client. +- In `src/index.tsx`, the list marks a post as visited when ``getQueryData(queryClient, [`/posts/${post.id}`])`` returns cached data. To run this example: diff --git a/examples/react/default-query-function/src/index.tsx b/examples/react/default-query-function/src/index.tsx index 5e53d30c7fe..e5d6a2fdbef 100644 --- a/examples/react/default-query-function/src/index.tsx +++ b/examples/react/default-query-function/src/index.tsx @@ -2,6 +2,9 @@ import { QueryClient, QueryClientProvider, defaultQueryFn, + getQueryData, + isFetching, + queryOptions, useQuery, useQueryClient, } from '@tanstack/react-query' @@ -66,10 +69,14 @@ function Posts({ }) { const queryClient = useQueryClient() - const { status, data, error, isFetching } = useQuery>({ - queryKey: ['/posts'], - queryFn: defaultQueryFn, - }) + const queryResult = useQuery( + queryOptions>({ + queryKey: ['/posts'], + queryFn: defaultQueryFn, + }), + ) + const { status, data, error } = queryResult + const fetching = isFetching(queryResult) return (
@@ -90,7 +97,7 @@ function Posts({ style={ // We can use the queryCache here to show bold links for // ones that are cached - queryClient.getQueryData([`/posts/${post.id}`]) + getQueryData(queryClient, [`/posts/${post.id}`]) ? { fontWeight: 'bold', color: 'green', @@ -103,7 +110,7 @@ function Posts({

))}
-
{isFetching ? 'Background Updating...' : ' '}
+
{fetching ? 'Background Updating...' : ' '}
)}
@@ -118,11 +125,15 @@ function Post({ postId: number setPostId: React.Dispatch> }) { - const { status, data, error, isFetching } = useQuery({ - queryKey: [`/posts/${postId}`], - queryFn: defaultQueryFn, - enabled: !!postId, - }) + const queryResult = useQuery( + queryOptions({ + queryKey: [`/posts/${postId}`], + queryFn: defaultQueryFn, + enabled: !!postId, + }), + ) + const { status, data, error } = queryResult + const fetching = isFetching(queryResult) return (
@@ -141,7 +152,7 @@ function Post({

{data.body}

-
{isFetching ? 'Background Updating...' : ' '}
+
{fetching ? 'Background Updating...' : ' '}
)}
diff --git a/examples/react/devtools-panel/src/index.tsx b/examples/react/devtools-panel/src/index.tsx index f6f16bc5a46..c710a507814 100644 --- a/examples/react/devtools-panel/src/index.tsx +++ b/examples/react/devtools-panel/src/index.tsx @@ -1,6 +1,8 @@ import { QueryClient, QueryClientProvider, + isFetching, + isPending, useQuery, } from '@tanstack/react-query' import { ReactQueryDevtoolsPanel } from '@tanstack/react-query-devtools' @@ -25,11 +27,13 @@ export default function App() { } function Example() { - const { isPending, error, data, isFetching } = useQuery(reposQueries.detail()) + const queryResult = useQuery(reposQueries.detail()) + const fetching = isFetching(queryResult) - 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} +
{fetching ? 'Updating...' : ''}
) } diff --git a/examples/react/eslint-plugin-demo/src/prefer-query-options-demo.tsx b/examples/react/eslint-plugin-demo/src/prefer-query-options-demo.tsx index d992faa55a8..354af02ca94 100644 --- a/examples/react/eslint-plugin-demo/src/prefer-query-options-demo.tsx +++ b/examples/react/eslint-plugin-demo/src/prefer-query-options-demo.tsx @@ -1,4 +1,11 @@ -import { useQuery, useQueryClient } from '@tanstack/react-query' +import { + useQuery, + useQueryClient, + queryOptions, + select, + invalidateQueries, + getQueryData, +} from '@tanstack/react-query' import { todoOptions, todosOptions } from './queries' // ✅ passes: consuming imported queryOptions result directly @@ -9,28 +16,33 @@ export function Todos() { // ✅ passes: spreading imported queryOptions result with additional options export function Todo({ id }: { id: string }) { - const query = useQuery({ - ...todoOptions(id), - select: (data) => data.title, - }) + const query = useQuery( + queryOptions({ + ...todoOptions(id), + select: [select, (data) => data.title], + }), + ) return query.data } // ✅ passes: referencing queryKey from imported queryOptions result export function invalidateTodos() { const queryClient = useQueryClient() - queryClient.invalidateQueries({ queryKey: todosOptions.queryKey }) + invalidateQueries(queryClient, { queryKey: todosOptions.queryKey }) } // ❌ fails: inline queryKey + queryFn should use queryOptions() export function TodosBad() { + // Raw options are rejected by the hook's public types as well as the rule. + /* eslint-disable @tanstack/query/prefer-query-options -- Demonstrates the inline options diagnostic. */ const query = useQuery( - // eslint-disable-next-line @tanstack/query/prefer-query-options -- Prefer using queryOptions() or infiniteQueryOptions() to co-locate queryKey and queryFn. + // @ts-expect-error -- a queryOptions descriptor is required { queryKey: ['todos'], queryFn: () => fetch('/api/todos').then((r) => r.json()), }, ) + /* eslint-enable @tanstack/query/prefer-query-options */ return query.data } @@ -38,12 +50,12 @@ export function TodosBad() { export function InvalidateTodosBad() { const queryClient = useQueryClient() // eslint-disable-next-line @tanstack/query/prefer-query-options -- Prefer referencing a queryKey from a queryOptions() result instead of typing it manually. - queryClient.invalidateQueries({ queryKey: ['todos'] }) + invalidateQueries(queryClient, { queryKey: ['todos'] }) } // ❌ fails: inline queryKey as direct parameter export function GetTodosDataBad() { const queryClient = useQueryClient() // eslint-disable-next-line @tanstack/query/prefer-query-options -- Prefer referencing a queryKey from a queryOptions() result instead of typing it manually. - return queryClient.getQueryData(['todos']) + return getQueryData(queryClient, ['todos']) } diff --git a/examples/react/hydration-nextjs-pages-router/README.md b/examples/react/hydration-nextjs-pages-router/README.md index 1f549fed5ba..3269166775a 100644 --- a/examples/react/hydration-nextjs-pages-router/README.md +++ b/examples/react/hydration-nextjs-pages-router/README.md @@ -7,7 +7,7 @@ Built with [Next.js (Pages Router)](https://nextjs.org/docs/pages). ## How it works - `src/services/posts/queries.ts` defines `postsQueries.list(limit)` with `queryOptions`, keyed by `['posts', 'list', limit]`. `src/services/posts/api.ts` fetches the posts from JSONPlaceholder and keeps the first `limit` of them. -- `src/pages/index.tsx` runs `queryClient.query(postsQueries.list(10))` on a fresh `QueryClient` in `getStaticProps` and returns `dehydrate(queryClient)` as `dehydratedState`. +- `src/pages/index.tsx` runs `query(queryClient, postsQueries.list(10))` on a fresh `QueryClient` in `getStaticProps` and returns `dehydrate(queryClient)` as `dehydratedState`. - `src/pages/_app.tsx` passes `pageProps.dehydratedState` to `HydrationBoundary`, and its `QueryClient` sets a `staleTime` of 1 minute, so the prefetched list is not refetched on mount while it is less than a minute old. Hydration keeps the time the data was fetched in `getStaticProps`, so a page served later than that refetches. - `src/components/PostList.tsx` reads `useQuery(postsQueries.list(postCount))`, and "Show More" raises `postCount` by 10, which fetches a new list. On `src/pages/client-only.tsx` the same component runs without prefetching, so the first list is fetched in the browser. diff --git a/examples/react/hydration-nextjs-pages-router/src/components/PostList.tsx b/examples/react/hydration-nextjs-pages-router/src/components/PostList.tsx index 99b68c74d17..226812ad958 100644 --- a/examples/react/hydration-nextjs-pages-router/src/components/PostList.tsx +++ b/examples/react/hydration-nextjs-pages-router/src/components/PostList.tsx @@ -1,21 +1,20 @@ -import { useQuery } from '@tanstack/react-query' +import { isError, isFetching, isPending, useQuery } from '@tanstack/react-query' import React, { useState } from 'react' import { postsQueries } from '../services/posts/queries' export const PostList = () => { const [postCount, setPostCount] = useState(10) - const { data, error, isPending, isError, isFetching } = useQuery( - postsQueries.list(postCount), - ) + const queryResult = useQuery(postsQueries.list(postCount)) + const fetching = isFetching(queryResult) - if (isPending) return
Loading
+ if (isPending(queryResult)) return
Loading
- if (isError) return
Error: {error.message}
+ if (isError(queryResult)) return
Error: {queryResult.error.message}
return (
    - {data.map((post, index) => ( + {queryResult.data.map((post, index) => (
  • {index + 1}. {post.title}
  • @@ -24,9 +23,9 @@ export const PostList = () => { {postCount <= 90 && ( )}