### Vue Query Setup with Queries, Mutations, and Invalidation
Source: https://tanstack.com/query/v5/docs/framework/vue/quick-start.md
Complete Vue 3 setup example showing how to use useQueryClient, useQuery, and useMutation hooks from @tanstack/vue-query. Demonstrates fetching todos, posting new todos, and invalidating queries on successful mutation. Includes template rendering with loading, error, and success states.
```vue
Loading...Error: {{ error.message }}
{{ todo.title }}
```
--------------------------------
### Install Dependencies and Start Development Server using npm
Source: https://tanstack.com/query/v5/docs/framework/vue/examples/nuxt3
This bash command first installs all project dependencies using npm, and then immediately starts the development server. This is a common combined command for initial setup and running the application.
```bash
npm install && npm run dev
```
--------------------------------
### React Query Setup with Queries, Mutations, and Invalidation
Source: https://tanstack.com/query/v5/docs/framework/react/quick-start.md
Complete React Query example demonstrating QueryClient setup, data fetching with useQuery, mutations with useMutation, and query invalidation. This snippet shows how to create a todo list application that fetches todos, displays them, and allows adding new todos with automatic cache invalidation. Requires @tanstack/react-query package and assumes getTodos and postTodo API functions are available.
```tsx
import {
useQuery,
useMutation,
useQueryClient,
QueryClient,
QueryClientProvider,
} from '@tanstack/react-query'
import { getTodos, postTodo } from '../my-api'
// Create a client
const queryClient = new QueryClient()
function App() {
return (
// Provide the client to your App
)
}
function Todos() {
// Access the client
const queryClient = useQueryClient()
// Queries
const query = useQuery({ queryKey: ['todos'], queryFn: getTodos })
// Mutations
const mutation = useMutation({
mutationFn: postTodo,
onSuccess: () => {
// Invalidate and refetch
queryClient.invalidateQueries({ queryKey: ['todos'] })
},
})
return (
{query.data?.map((todo) => (
{todo.title}
))}
)
}
render(, document.getElementById('root'))
```
--------------------------------
### Start Svelte Development Server
Source: https://tanstack.com/query/v5/docs/framework/svelte/examples/load-more-infinite-scroll
Launch the development server for a Svelte project after installing dependencies. The --open flag automatically opens the app in a new browser tab.
```bash
npm run dev
```
```bash
npm run dev -- --open
```
--------------------------------
### Fetch Data using useQuery in SolidJS
Source: https://tanstack.com/query/v5/docs/framework/solid/quick-start.md
This example demonstrates the basic setup for TanStack Query in a SolidJS application. It covers initializing the QueryClient, using the QueryClientProvider, and fetching data with the useQuery hook while handling loading, error, and success states using SolidJS control flow components.
```tsx
import {
QueryClient,
QueryClientProvider,
useQuery,
} from '@tanstack/solid-query'
import { Switch, Match, For } from 'solid-js'
const queryClient = new QueryClient()
function Example() {
const query = useQuery(() => ({
queryKey: ['todos'],
queryFn: fetchTodos,
}))
return (
Loading...
Error: {query.error.message}
{(todo) =>
{todo.title}
}
)
}
function App() {
return (
)
}
```
--------------------------------
### Nuxt 3 Project Setup and Development
Source: https://tanstack.com/query/v5/docs/framework/vue/examples/nuxt3
Basic setup instructions for a Nuxt 3 minimal starter project. Includes dependency installation, development server startup on localhost:3000, and production build commands. Requires Node.js and yarn package manager.
```bash
yarn install
```
```bash
yarn dev
```
```bash
yarn build
```
--------------------------------
### Setup QueryClient and Preact Query Provider
Source: https://tanstack.com/query/v5/docs/framework/preact/quick-start.md
Initializes a QueryClient instance and wraps the application with QueryClientProvider to enable Preact Query functionality throughout the component tree. This is the foundational setup required for all Preact Query features.
```tsx
import {
useQuery,
useMutation,
useQueryClient,
QueryClient,
QueryClientProvider,
} from '@tanstack/preact-query'
import { getTodos, postTodo } from '../my-api'
// Create a client
const queryClient = new QueryClient()
function App() {
return (
// Provide the client to your App
)
}
```
--------------------------------
### Setup Root App Component with QueryClientProvider
Source: https://tanstack.com/query/v5/docs/framework/solid/examples/basic
Wraps the application with QueryClientProvider to make the QueryClient available to all child components. Includes SolidQueryDevtools for debugging and manages post selection state with conditional rendering.
```typescript
const App: Component = () => {
const [postId, setPostId] = createSignal(-1)
return (
As you visit the posts below, you will notice them in a loading state
the first time you load them. However, after you return to this list and
click on any posts you have already visited again, you will see them
load instantly and background refresh right before your eyes!
{postId() > -1 ? (
) : (
)}
)
}
const root = document.getElementById('root')
if (!root) throw new Error('Missing #root element')
render(() => , root)
```
--------------------------------
### Initialize QueryClient and Setup Provider in Solid.js
Source: https://tanstack.com/query/v5/docs/framework/solid/examples/simple
Creates a QueryClient instance and wraps the application with QueryClientProvider to enable query functionality across the component tree. The SolidQueryDevtools component is included for development debugging and monitoring of queries.
```typescript
/* @refresh reload */
import {
QueryClient,
QueryClientProvider,
useQuery,
} from '@tanstack/solid-query'
import { SolidQueryDevtools } from '@tanstack/solid-query-devtools'
import { Match, Switch } from 'solid-js'
import { render } from 'solid-js/web'
const queryClient = new QueryClient()
export default function App() {
return (
)
}
```
--------------------------------
### Start Svelte development server with npm
Source: https://tanstack.com/query/v5/docs/framework/svelte/examples/auto-refetching
This snippet provides commands to start the development server for a Svelte project. After installing dependencies, `npm run dev` launches the server, and `npm run dev -- --open` automatically opens the application in a new browser tab for convenience during development.
```bash
npm run dev
# or start the server and open the app in a new browser tab
npm run dev -- --open
```
--------------------------------
### Use TanStack Vue Query with Vue 3 Composition API and
...
```
--------------------------------
### Install React Query via Bun
Source: https://tanstack.com/query/v5/docs/framework/react/installation.md
Install @tanstack/react-query package using Bun package manager as an alternative to NPM.
```bash
bun add @tanstack/react-query
```
--------------------------------
### Setup QueryClient with Preact Provider
Source: https://tanstack.com/query/v5/docs/framework/preact/examples/simple
Initializes TanStack Query v5 with Preact by creating a QueryClient instance and wrapping the application with QueryClientProvider. This enables query caching and state management across the component tree.
```typescript
import { render } from 'preact'
import {
QueryClient,
QueryClientProvider,
useQuery,
} from '@tanstack/preact-query'
const queryClient = new QueryClient()
export function App() {
return (
)
}
```
--------------------------------
### Install ESLint Plugin Query via Bun
Source: https://tanstack.com/query/v5/docs/framework/react/installation.md
Install @tanstack/eslint-plugin-query as a development dependency using Bun package manager.
```bash
bun add -D @tanstack/eslint-plugin-query
```
--------------------------------
### Install React Query via Yarn
Source: https://tanstack.com/query/v5/docs/framework/react/installation.md
Install @tanstack/react-query package using Yarn package manager as an alternative to NPM.
```bash
yarn add @tanstack/react-query
```
--------------------------------
### React Application Root Setup
Source: https://tanstack.com/query/v5/docs/framework/react/examples/playground
Initializes the React application by mounting the root component to the DOM element with ID 'root' using React 19's createRoot API.
```TypeScript
const rootElement = document.getElementById('root') as HTMLElement
ReactDOM.createRoot(rootElement).render()
```
--------------------------------
### Configure Vite with Preact Plugin
Source: https://tanstack.com/query/v5/docs/framework/preact/examples/simple
Vite configuration file that enables Preact preset plugin for optimized bundling and development server setup with hot module replacement support.
```typescript
import { defineConfig } from 'vite'
import preact from '@preact/preset-vite'
export default defineConfig({
plugins: [preact()],
})
```
--------------------------------
### Create a new Svelte project using npm
Source: https://tanstack.com/query/v5/docs/framework/svelte/examples/auto-refetching
This snippet demonstrates how to initialize a new Svelte project using the `npm create svelte@latest` command. It provides examples for creating a project in the current directory or within a specified new directory, setting up the basic Svelte application structure.
```bash
# create a new project in the current directory
npm create svelte@latest
# create a new project in my-app
npm create svelte@latest my-app
```
--------------------------------
### Import TanStack Preact Query via CDN (ESM.sh)
Source: https://tanstack.com/query/v5/docs/framework/preact/installation.md
Example of how to import Preact and TanStack Preact Query directly into an HTML file using an ESM-compatible CDN like ESM.sh. This method is suitable for projects not using module bundlers.
```html
```
--------------------------------
### Initialize QueryClient and Setup QueryClientProvider in React
Source: https://tanstack.com/query/v5/docs/framework/react/examples/simple
Sets up TanStack Query v5 in a React application by creating a QueryClient instance and wrapping the app with QueryClientProvider. This enables query caching, synchronization, and state management across the application. Includes React Query Devtools for debugging query state in development.
```TypeScript
import React from 'react'
import ReactDOM from 'react-dom/client'
import {
QueryClient,
QueryClientProvider,
useQuery,
} from '@tanstack/react-query'
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
const queryClient = new QueryClient()
export default function App() {
return (
)
}
function Example() {
const { isPending, error, data, isFetching } = useQuery({
// query configuration here
})
}
```
--------------------------------
### useQuery with Required Parameters
Source: https://tanstack.com/query/v5/docs/framework/solid/reference/useQuery.md
Example useQuery hook invocation with required parameters queryKey and queryFn. Demonstrates basic query setup where queryKey identifies the query and queryFn provides the data fetching function that returns a Promise.
```typescript
const { data, isLoading, error } = useQuery({
queryKey: ['todos'],
queryFn: async () => {
const response = await fetch('/api/todos');
if (!response.ok) throw new Error('Failed to fetch todos');
return response.json();
}
});
```
--------------------------------
### Vite Configuration with Solid.js Plugin
Source: https://tanstack.com/query/v5/docs/framework/solid/examples/simple
Vite build configuration that integrates the Solid.js plugin for JSX transformation and development server setup. This minimal configuration enables fast HMR (Hot Module Replacement) and optimized production builds for Solid.js applications.
```typescript
import { defineConfig } from 'vite'
import solid from 'vite-plugin-solid'
export default defineConfig({
plugins: [solid()]
})
```
--------------------------------
### Install Project Dependencies using Yarn
Source: https://tanstack.com/query/v5/docs/framework/vue/examples/nuxt3
This bash command installs all required project dependencies as defined in the `package.json` file using the Yarn package manager.
```bash
yarn install
```
--------------------------------
### Project Lifecycle Commands for Nuxt 3
Source: https://tanstack.com/query/v5/docs/framework/vue/examples/nuxt3
Standard CLI commands to install dependencies, launch the development server, and generate a production build using yarn.
```bash
# Install dependencies
yarn install
# Start development server
yarn dev
# Build for production
yarn build
```
--------------------------------
### Start Nuxt 3 Development Server using Yarn
Source: https://tanstack.com/query/v5/docs/framework/vue/examples/nuxt3
This bash command starts the Nuxt 3 development server, typically accessible at `http://localhost:3000`, enabling hot module reloading and live development.
```bash
yarn dev
```
--------------------------------
### Node.js Package Dependency Definitions in package-lock.json
Source: https://tanstack.com/query/v5/docs/framework/vue/examples/nuxt3
This JSON snippet provides examples of package dependency entries found in a `package-lock.json` file. It details package versions, resolved URLs, integrity hashes, and their respective sub-dependencies, which are critical for ensuring consistent and reproducible builds across different development environments.
```json
"dev": true, "requires": { "@vue/devtools-api": "^6.6.4" } }, "webidl-conversions": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", "dev": true }, "webpack-virtual-modules": { "version": "0.6.2", "resolved": "https://registry.npmjs.org/webpack-virtual-modules/-/webpack-virtual-modules-0.6.2.tgz", "integrity": "sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ==", "dev": true }, "whatwg-url": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", "dev": true, "requires": { "tr46": "~0.0.3", "webidl-conversions": "^3.0.0" } }, "which": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/which/-/which-6.0.1.tgz", "integrity": "sha512-oGLe46MIrCRqX7ytPUf66EAYvdeMIZYn3WaocqqKZAxrBpkqHfL/qvTyJ/bTk5+AqHCjXmrv3CEWgy368zhRUg==", "dev": true, "requires": { "isexe": "^4.0.0" } }, "wrap-ansi": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", "dev": true, "requires": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "wrap-ansi-cjs": { "version": "npm:wrap-ansi@7.0.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", "dev": true, "requires": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "ws": { "version": "8.19.0", "resolved": "https://registry.npmjs.org/ws/-/ws-8.19.0.tgz", "integrity": "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg==", "dev": true }, "wsl-utils": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/wsl-utils/-/wsl-utils-0.1.0.tgz", "integrity": "sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw==", "dev": true, "requires": { "is-wsl": "^3.1.0" } }, "y18n": { "version": "5.0.8", "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", "dev": true }, "yallist": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", "dev": true }, "yaml": { "version": "2.8.2", "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.2.tgz", "integrity": "sha512-mplynKqc1C2hTVYxd0PU2xQAc22TI1vShAYGksCCfxbn/dFwnHTNi1bvYsBTkhdUNtGIf5xNOg938rrSSYvS9A==", "dev": true }, "yargs": { "version": "17.7.2", "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", "dev": true, "requires": { "cliui": "^8.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.3", "y18n": "^5.0.5", "yargs-parser": "^21.1.1" } }, "yargs-parser": { "version": "21.1.1", "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", "dev": true }, "youch": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/youch/-/youch-4.1.0.tgz", "integrity": "sha512-cYekNh2tUoU+voS11X0D0UQntVCSO6LQ1h10VriQGmfbpf0mnGTruwZICts23UUNiZCXm8H8hQBtRrdsbhuNNg==", "dev": true, "requires": { "@poppinss/colors": "^4.1.6", "@poppinss/dumper": "^0.7.0", "@speed-highlight/core": "^1.2.14", "cookie-es": "^2.0.0", "youch-core": "^0.3.3" } }, "youch-core": { "version": "0.3.3", "resolved": "https://registry.npmjs.org/youch-core/-/youch-core-0.3.3.tgz", "integrity": "sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA==", "dev": true, "requires": { "@poppinss/exception": "^1.2.2", "error-stack-parser-es": "^1.0.5" } }, "zip-stream": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/zip-stream/-/zip-stream-6.0.1.tgz", "integrity": "sha512-zK7YHHz4ZXpW89AHXUPbQVGKI7uvkd3hzusTdotCg1UxyaVtg0zFJSTfW/Dq5f7OBBVnq6cZIaC8Ti4hb6dtCA==", "dev": true, "requires": { "archiver-utils": "^5.0.0", "compress-commons": "^6.0.2", "readable-stream": "^4.0.0" } } } }
```
--------------------------------
### Initialize Angular Project Environment
Source: https://tanstack.com/query/v5/docs/framework/angular/examples/auto-refetching
Terminal commands used to install project dependencies and start the local development server for the Angular TanStack Query example.
```bash
npm install && npm start
```
--------------------------------
### Provide TanStack Query Client to Angular App
Source: https://tanstack.com/query/v5/docs/framework/angular/quick-start.md
Initialize and provide the QueryClient to your Angular application using the provideTanStackQuery function. This example shows setup for standalone bootstrap applications. The QueryClient manages query caching and synchronization across your app.
```typescript
import { provideHttpClient } from '@angular/common/http'
import {
provideTanStackQuery,
QueryClient,
} from '@tanstack/angular-query-experimental'
bootstrapApplication(AppComponent, {
providers: [provideHttpClient(), provideTanStackQuery(new QueryClient())],
})
```
--------------------------------
### Install @tanstack/query-persist-client-core package
Source: https://tanstack.com/query/v5/docs/framework/preact/plugins/createPersister.md
Instructions for installing the @tanstack/query-persist-client-core package, which provides the experimental_createQueryPersister utility. This utility is also included in @tanstack/preact-query-persist-client, so separate installation is not needed if using that package.
```bash
npm install @tanstack/query-persist-client-core
```
```bash
pnpm add @tanstack/query-persist-client-core
```
```bash
yarn add @tanstack/query-persist-client-core
```
```bash
bun add @tanstack/query-persist-client-core
```
--------------------------------
### Install ESLint Plugin Query via Yarn
Source: https://tanstack.com/query/v5/docs/framework/react/installation.md
Install @tanstack/eslint-plugin-query as a development dependency using Yarn package manager.
```bash
yarn add -D @tanstack/eslint-plugin-query
```
--------------------------------
### Initialize App with QueryClientProvider and Routing Logic
Source: https://tanstack.com/query/v5/docs/framework/solid/examples/basic
Root SolidJS component that wraps the application with QueryClientProvider and SolidQueryDevtools. Manages postId state and conditionally renders either the Posts list or Post detail view based on selection.
```TypeScript
const App: Component = () => {
const [postId, setPostId] = createSignal(-1)
return (
As you visit the posts below, you will notice them in a loading state
the first time you load them. However, after you return to this list and
click on any posts you have already visited again, you will see them
load instantly and background refresh right before your eyes!{' '}
(You may need to throttle your network speed to simulate longer
loading sequences)
{postId() > -1 ? (
) : (
)}
)
}
```
--------------------------------
### Install ESLint Plugin Query via PNPM
Source: https://tanstack.com/query/v5/docs/framework/react/installation.md
Install @tanstack/eslint-plugin-query as a development dependency using PNPM package manager.
```bash
pnpm add -D @tanstack/eslint-plugin-query
```
--------------------------------
### Fetch Repository Data with useQuery Hook
Source: https://tanstack.com/query/v5/docs/framework/preact/examples/simple
Implements the useQuery hook to fetch GitHub repository data asynchronously. Returns loading state (isPending), error handling, fetched data, and isFetching flag for UI updates. The query is cached with the key 'repoData'.
```typescript
const Example = () => {
const { isPending, error, data, isFetching } = useQuery({
queryKey: ['repoData'],
queryFn: async () => {
const response = await fetch(
'https://api.github.com/repos/tanstack/query'
)
return response.json()
},
})
return (
{data?.full_name}
{data?.description}
{isFetching ? 'Updating...' : ''}
)
}
```
--------------------------------
### Install React Query via PNPM
Source: https://tanstack.com/query/v5/docs/framework/react/installation.md
Install @tanstack/react-query package using PNPM package manager as an alternative to NPM.
```bash
pnpm add @tanstack/react-query
```
--------------------------------
### Fetch Data with useQuery Hook
Source: https://tanstack.com/query/v5/docs/framework/preact/quick-start.md
Demonstrates fetching data using the useQuery hook with a query key and query function. The hook automatically manages loading, error, and data states, and provides access to the fetched todos data.
```tsx
function Todos() {
// Access the client
const queryClient = useQueryClient()
// Queries
const query = useQuery({ queryKey: ['todos'], queryFn: getTodos })
return (
{query.data?.map((todo) => (
{todo.title}
))}
)
}
```
--------------------------------
### Basic useQuery Implementation with API Fetch
Source: https://tanstack.com/query/v5/docs/framework/solid/reference/useQuery.md
Shows a basic example of using useQuery to fetch todos from an API endpoint. Demonstrates handling error, loading, and success states using Solid's Show component to conditionally render UI based on query status.
```tsx
import { useQuery } from '@tanstack/solid-query'
function App() {
const todos = useQuery(() => ({
queryKey: 'todos',
queryFn: async () => {
const response = await fetch('/api/todos')
if (!response.ok) {
throw new Error('Failed to fetch todos')
}
return response.json()
},
}))
return (
Error: {todos.error.message}
Loading...
Todos:
{(todo) =>
{todo.title}
}
)
}
```
--------------------------------
### Install React Query via NPM
Source: https://tanstack.com/query/v5/docs/framework/react/installation.md
Install @tanstack/react-query package using NPM package manager. This is the primary installation method for projects using Node.js and npm.
```bash
npm i @tanstack/react-query
```
--------------------------------
### Install @tanstack/query-sync-storage-persister and persist-client
Source: https://tanstack.com/query/v5/docs/framework/react/plugins/createSyncStoragePersister.md
Instructions for installing the necessary packages, `@tanstack/query-sync-storage-persister` and `@tanstack/react-query-persist-client`, using various JavaScript package managers.
```bash
npm install @tanstack/query-sync-storage-persister @tanstack/react-query-persist-client
```
```bash
pnpm add @tanstack/query-sync-storage-persister @tanstack/react-query-persist-client
```
```bash
yarn add @tanstack/query-sync-storage-persister @tanstack/react-query-persist-client
```
```bash
bun add @tanstack/query-sync-storage-persister @tanstack/react-query-persist-client
```
--------------------------------
### Vite Configuration with React Plugin
Source: https://tanstack.com/query/v5/docs/framework/react/examples/simple
Configuration file for the Vite build tool, utilizing the official React plugin to handle JSX and Fast Refresh.
```typescript
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
})
```
--------------------------------
### Install ESLint Plugin Query via NPM
Source: https://tanstack.com/query/v5/docs/framework/react/installation.md
Install @tanstack/eslint-plugin-query as a development dependency using NPM. This plugin helps catch bugs and inconsistencies in React Query code during development.
```bash
npm i -D @tanstack/eslint-plugin-query
```
--------------------------------
### Define Project Dependencies and Scripts for TanStack Solid Query Example
Source: https://tanstack.com/query/v5/docs/framework/solid/examples/simple
This `package.json` file defines the project's metadata, scripts, and dependencies for a TanStack Solid Query example. It includes `@tanstack/solid-query`, `@tanstack/solid-query-devtools`, and `solid-js` as core dependencies, along with development tools like `typescript`, `vite`, and `vite-plugin-solid` for building and serving the application.
```json
{
"name": "@tanstack/query-example-solid-simple",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"@tanstack/solid-query": "^5.90.26",
"@tanstack/solid-query-devtools": "^5.91.3",
"solid-js": "^1.9.7"
},
"devDependencies": {
"@tanstack/eslint-plugin-query": "^5.91.4",
"typescript": "5.8.3",
"vite": "^6.4.1",
"vite-plugin-solid": "^2.11.6"
}
}
```
--------------------------------
### Fetch GitHub Repo Data with TanStack Query in Preact
Source: https://tanstack.com/query/v5/docs/framework/preact/examples/simple
This Preact component demonstrates how to integrate `@tanstack/preact-query` to fetch data from the GitHub API. It initializes a `QueryClient`, wraps the application with `QueryClientProvider`, and uses the `useQuery` hook within an `Example` component to manage data fetching, loading states, and error handling. The fetched data (repository name, description, and stats) is then rendered.
```tsx
import { render } from 'preact'
import {
QueryClient,
QueryClientProvider,
useQuery,
} from '@tanstack/preact-query'
const queryClient = new QueryClient()
export function App() {
return (
)
}
const Example = () => {
const { isPending, error, data, isFetching } = useQuery({
queryKey: ['repoData'],
queryFn: async () => {
const response = await fetch(
'https://api.github.com/repos/TanStack/query',
)
return await response.json()
},
})
if (isPending) return 'Loading...'
if (error !== null) return 'An error has occurred: ' + error.message
return (
)
}
const app = document.getElementById('app')
if (!app) throw new Error('Missing #app element')
render(, app)
```
--------------------------------
### Build a React Chat UI using TanStack Query v5
Source: https://tanstack.com/query/v5/docs/framework/react/examples/chat
This snippet demonstrates the core implementation of a chat application. It includes the QueryClient setup, a ChatMessage component that fetches data using useQuery, and a main Example component for managing the message list and user input.
```tsx
import ReactDOM from 'react-dom/client'
import {
QueryClient,
QueryClientProvider,
useQuery,
} from '@tanstack/react-query'
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
import './style.css'
import { useState } from 'react'
import { chatQueryOptions } from './chat'
import { Message } from './message'
const queryClient = new QueryClient()
export default function App() {
return (
)
}
function ChatMessage({ question }: { question: string }) {
const { error, data = [], isFetching } = useQuery(chatQueryOptions(question))
if (error) return 'An error has occurred: ' + error.message
return (
setCurrentQuestion(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
submitMessage()
}
}}
placeholder="Type your message..."
/>
)
}
const rootElement = document.getElementById('root') as HTMLElement
ReactDOM.createRoot(rootElement).render()
```
--------------------------------
### Initialize and Render React Application with ReactDOM
Source: https://tanstack.com/query/v5/docs/framework/react/examples/algolia
This snippet demonstrates the standard entry point for a React application using `ReactDOM.createRoot`. It imports `ReactDOM` and the main `App` component, then mounts the application to a DOM element with the ID 'root' for rendering.
```tsx
import ReactDOM from 'react-dom/client'
import App from './App'
const rootElement = document.getElementById('root') as HTMLElement
ReactDOM.createRoot(rootElement).render()
```
--------------------------------
### Configure QueryClient with experimental_createQueryPersister
Source: https://tanstack.com/query/v5/docs/framework/preact/plugins/createPersister.md
This example demonstrates how to import experimental_createQueryPersister, create a persister instance using AsyncStorage, and integrate it into the QueryClient's defaultOptions. It shows setting maxAge for persisted data and gcTime for garbage collection, enabling all queries to be persisted individually.
```tsx
import AsyncStorage from '@react-native-async-storage/async-storage'
import { QueryClient } from '@tanstack/preact-query'
import { experimental_createQueryPersister } from '@tanstack/query-persist-client-core'
const persister = experimental_createQueryPersister({
storage: AsyncStorage,
maxAge: 1000 * 60 * 60 * 12, // 12 hours
})
const queryClient = new QueryClient({
defaultOptions: {
queries: {
gcTime: 1000 * 30, // 30 seconds
persister: persister.persisterFn,
},
},
})
```
--------------------------------
### Define Component Props with TypeScript in Vue
Source: https://tanstack.com/query/v5/docs/framework/vue/reactivity.md
Defines a Vue component with a typed prop using the Composition API setup syntax. This establishes the userId prop that will be used in query examples.
```vue
```
--------------------------------
### Initialize TanStack Query and Devtools in SolidJS App
Source: https://tanstack.com/query/v5/docs/framework/solid/examples/basic-graphql-request
This code defines the main `App` component for a SolidJS application. It sets up the `QueryClientProvider` to make the TanStack Query client available throughout the component tree and integrates `SolidQueryDevtools` for debugging. It also manages the `postId` state to switch between displaying a list of posts and a single post's details.
```typescript
import { SolidQueryDevtools } from '@tanstack/solid-query-devtools'
import { For, Match, Switch, createSignal } from 'solid-js'
import { render } from 'solid-js/web'
import { gql, request } from 'graphql-request'
import type { Accessor, Setter } from 'solid-js'
const endpoint = 'https://graphqlzero.almansi.me/api'
const queryClient = new QueryClient()
type Post = {
id: number
title: string
body: string
}
function App() {
const [postId, setPostId] = createSignal(-1)
return (
As you visit the posts below, you will notice them in a loading state
the first time you load them. However, after you return to this list and
click on any posts you have already visited again, you will see them
load instantly and background refresh right before your eyes! {' '}
(You may need to throttle your network speed to simulate longer
loading sequences)
{postId() > -1 ? (
) : (
)}
)
}
```
--------------------------------
### Get mutation data by mutationKey using useMutationState
Source: https://tanstack.com/query/v5/docs/framework/solid/reference/useMutationState.md
Shows how to retrieve data for specific mutations by matching the mutationKey. This example creates a mutation with a specific key and then uses useMutationState to access the state data for mutations matching that key.
```tsx
import { useMutation, useMutationState } from '@tanstack/solid-query'
const mutationKey = ['posts']
// Some mutation that we want to get the state for
const mutation = useMutation(() => ({
mutationKey,
mutationFn: (newPost) => {
return axios.post('/posts', newPost)
},
}))
const data = useMutationState(() => ({
// this mutation key needs to match the mutation key of the given mutation (see above)
filters: { mutationKey },
select: (mutation) => mutation.state.data,
}))
```
--------------------------------
### Fetch GitHub Repository Data with TanStack Solid Query
Source: https://tanstack.com/query/v5/docs/framework/solid/examples/simple
This SolidJS component demonstrates how to use `@tanstack/solid-query` to fetch data from the GitHub API. It initializes a `QueryClientProvider` at the root and uses the `useQuery` hook within an `Example` component to retrieve repository information, dynamically handling loading, error, and data display states.
```tsx
/* @refresh reload */
import {
QueryClient,
QueryClientProvider,
useQuery,
} from '@tanstack/solid-query'
import { SolidQueryDevtools } from '@tanstack/solid-query-devtools'
import { Match, Switch } from 'solid-js'
import { render } from 'solid-js/web'
const queryClient = new QueryClient()
export default function App() {
return (
)
}
function Example() {
const state = useQuery(() => ({
queryKey: ['repoData'],
queryFn: async () => {
const response = await fetch(
'https://api.github.com/repos/TanStack/query',
)
return await response.json()
},
}))
return (
Loading...
{'An error has occurred: ' + (state.error as Error).message}