snapshot of https://github.com/TanStack/query.git (main, 2026-09-16; blobs > 131072B omitted)
This commit is contained in:
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"name": "Node.js",
|
||||
"image": "mcr.microsoft.com/devcontainers/javascript-node:22"
|
||||
}
|
||||
6
examples/angular/auto-refetching/.eslintrc.cjs
Normal file
6
examples/angular/auto-refetching/.eslintrc.cjs
Normal file
@@ -0,0 +1,6 @@
|
||||
// @ts-check
|
||||
|
||||
/** @type {import('eslint').Linter.Config} */
|
||||
const config = {}
|
||||
|
||||
module.exports = config
|
||||
6
examples/angular/auto-refetching/README.md
Normal file
6
examples/angular/auto-refetching/README.md
Normal file
@@ -0,0 +1,6 @@
|
||||
# TanStack Query Angular auto-refetching example
|
||||
|
||||
To run this example:
|
||||
|
||||
- `pnpm install`
|
||||
- `pnpm start`
|
||||
130
examples/angular/auto-refetching/angular.json
Normal file
130
examples/angular/auto-refetching/angular.json
Normal file
@@ -0,0 +1,130 @@
|
||||
{
|
||||
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
|
||||
"version": 1,
|
||||
"cli": {
|
||||
"packageManager": "pnpm",
|
||||
"analytics": false,
|
||||
"cache": {
|
||||
"enabled": false
|
||||
}
|
||||
},
|
||||
"newProjectRoot": "projects",
|
||||
"projects": {
|
||||
"auto-refetching": {
|
||||
"projectType": "application",
|
||||
"schematics": {
|
||||
"@schematics/angular:component": {
|
||||
"inlineTemplate": true,
|
||||
"inlineStyle": true,
|
||||
"skipTests": true
|
||||
},
|
||||
"@schematics/angular:class": {
|
||||
"skipTests": true
|
||||
},
|
||||
"@schematics/angular:directive": {
|
||||
"skipTests": true
|
||||
},
|
||||
"@schematics/angular:guard": {
|
||||
"skipTests": true
|
||||
},
|
||||
"@schematics/angular:interceptor": {
|
||||
"skipTests": true
|
||||
},
|
||||
"@schematics/angular:pipe": {
|
||||
"skipTests": true
|
||||
},
|
||||
"@schematics/angular:resolver": {
|
||||
"skipTests": true
|
||||
},
|
||||
"@schematics/angular:service": {
|
||||
"skipTests": true
|
||||
}
|
||||
},
|
||||
"root": "",
|
||||
"sourceRoot": "src",
|
||||
"prefix": "app",
|
||||
"architect": {
|
||||
"build": {
|
||||
"builder": "@angular/build:application",
|
||||
"options": {
|
||||
"outputPath": "dist/auto-refetching",
|
||||
"index": "src/index.html",
|
||||
"browser": "src/main.ts",
|
||||
"polyfills": ["zone.js"],
|
||||
"tsConfig": "tsconfig.app.json",
|
||||
"assets": ["src/favicon.ico", "src/assets"],
|
||||
"styles": [],
|
||||
"scripts": []
|
||||
},
|
||||
"configurations": {
|
||||
"production": {
|
||||
"budgets": [
|
||||
{
|
||||
"type": "initial",
|
||||
"maximumWarning": "500kb",
|
||||
"maximumError": "1mb"
|
||||
},
|
||||
{
|
||||
"type": "anyComponentStyle",
|
||||
"maximumWarning": "2kb",
|
||||
"maximumError": "4kb"
|
||||
}
|
||||
],
|
||||
"outputHashing": "all"
|
||||
},
|
||||
"development": {
|
||||
"optimization": false,
|
||||
"extractLicenses": false,
|
||||
"sourceMap": true
|
||||
}
|
||||
},
|
||||
"defaultConfiguration": "production"
|
||||
},
|
||||
"serve": {
|
||||
"builder": "@angular/build:dev-server",
|
||||
"configurations": {
|
||||
"production": {
|
||||
"buildTarget": "auto-refetching:build:production"
|
||||
},
|
||||
"development": {
|
||||
"buildTarget": "auto-refetching:build:development"
|
||||
}
|
||||
},
|
||||
"defaultConfiguration": "development"
|
||||
},
|
||||
"extract-i18n": {
|
||||
"builder": "@angular/build:extract-i18n",
|
||||
"options": {
|
||||
"buildTarget": "auto-refetching:build"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"schematics": {
|
||||
"@schematics/angular:component": {
|
||||
"type": "component"
|
||||
},
|
||||
"@schematics/angular:directive": {
|
||||
"type": "directive"
|
||||
},
|
||||
"@schematics/angular:service": {
|
||||
"type": "service"
|
||||
},
|
||||
"@schematics/angular:guard": {
|
||||
"typeSeparator": "."
|
||||
},
|
||||
"@schematics/angular:interceptor": {
|
||||
"typeSeparator": "."
|
||||
},
|
||||
"@schematics/angular:module": {
|
||||
"typeSeparator": "."
|
||||
},
|
||||
"@schematics/angular:pipe": {
|
||||
"typeSeparator": "."
|
||||
},
|
||||
"@schematics/angular:resolver": {
|
||||
"typeSeparator": "."
|
||||
}
|
||||
}
|
||||
}
|
||||
27
examples/angular/auto-refetching/package.json
Normal file
27
examples/angular/auto-refetching/package.json
Normal file
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "@tanstack/query-example-angular-auto-refetching",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"ng": "ng",
|
||||
"start": "ng serve",
|
||||
"build": "ng build",
|
||||
"watch": "ng build --watch --configuration development"
|
||||
},
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@angular/common": "^20.0.0",
|
||||
"@angular/compiler": "^20.0.0",
|
||||
"@angular/core": "^20.0.0",
|
||||
"@angular/platform-browser": "^20.0.0",
|
||||
"@tanstack/angular-query-experimental": "^5.102.8",
|
||||
"rxjs": "^7.8.2",
|
||||
"tslib": "^2.8.1",
|
||||
"zone.js": "0.15.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@angular/build": "^20.0.0",
|
||||
"@angular/cli": "^20.0.0",
|
||||
"@angular/compiler-cli": "^20.0.0",
|
||||
"typescript": "5.8.3"
|
||||
}
|
||||
}
|
||||
10
examples/angular/auto-refetching/src/app/app.component.ts
Normal file
10
examples/angular/auto-refetching/src/app/app.component.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { ChangeDetectionStrategy, Component } from '@angular/core'
|
||||
import { AutoRefetchingExampleComponent } from './components/auto-refetching.component'
|
||||
|
||||
@Component({
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
selector: 'app-root',
|
||||
template: `<auto-refetching-example />`,
|
||||
imports: [AutoRefetchingExampleComponent],
|
||||
})
|
||||
export class AppComponent {}
|
||||
28
examples/angular/auto-refetching/src/app/app.config.ts
Normal file
28
examples/angular/auto-refetching/src/app/app.config.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import {
|
||||
provideHttpClient,
|
||||
withFetch,
|
||||
withInterceptors,
|
||||
} from '@angular/common/http'
|
||||
import {
|
||||
QueryClient,
|
||||
provideTanStackQuery,
|
||||
} from '@tanstack/angular-query-experimental'
|
||||
import { withDevtools } from '@tanstack/angular-query-experimental/devtools'
|
||||
import { mockInterceptor } from './interceptor/mock-api.interceptor'
|
||||
import type { ApplicationConfig } from '@angular/core'
|
||||
|
||||
export const appConfig: ApplicationConfig = {
|
||||
providers: [
|
||||
provideHttpClient(withFetch(), withInterceptors([mockInterceptor])),
|
||||
provideTanStackQuery(
|
||||
new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
gcTime: 1000 * 60 * 60 * 24, // 24 hours
|
||||
},
|
||||
},
|
||||
}),
|
||||
withDevtools(),
|
||||
),
|
||||
],
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<div>
|
||||
<h1>Auto Refetch with stale-time set to {{ intervalMs() }}ms</h1>
|
||||
<p>
|
||||
This example is best experienced on your own machine, where you can open
|
||||
multiple tabs to the same localhost server and see your changes propagate
|
||||
between the two.
|
||||
</p>
|
||||
<label>
|
||||
Query Interval speed (ms):
|
||||
<input [value]="intervalMs()" (input)="inputChange($event)" />
|
||||
<span
|
||||
[ngStyle]="{
|
||||
display: 'inline-block',
|
||||
marginLeft: '.5rem',
|
||||
width: '10px',
|
||||
height: '10px',
|
||||
background: tasks.isFetching() ? 'green' : 'transparent',
|
||||
transition: !tasks.isFetching() ? 'all .3s ease' : 'none',
|
||||
borderRadius: '100%',
|
||||
transform: 'scale(2)',
|
||||
}"
|
||||
></span>
|
||||
</label>
|
||||
<h2>Todo List</h2>
|
||||
|
||||
<input placeholder="Enter something" (keydown.enter)="addItem($event)" />
|
||||
<ul>
|
||||
@for (item of tasks.data(); track item) {
|
||||
<li>{{ item }}</li>
|
||||
}
|
||||
</ul>
|
||||
<div>
|
||||
<button (click)="clearTasks()">Clear All</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,49 @@
|
||||
import {
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
inject,
|
||||
signal,
|
||||
} from '@angular/core'
|
||||
import {
|
||||
injectMutation,
|
||||
injectQuery,
|
||||
} from '@tanstack/angular-query-experimental'
|
||||
import { NgStyle } from '@angular/common'
|
||||
import { TasksService } from '../services/tasks.service'
|
||||
|
||||
@Component({
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
selector: 'auto-refetching-example',
|
||||
templateUrl: './auto-refetching.component.html',
|
||||
imports: [NgStyle],
|
||||
})
|
||||
export class AutoRefetchingExampleComponent {
|
||||
readonly #tasksService = inject(TasksService)
|
||||
|
||||
readonly intervalMs = signal(1000)
|
||||
|
||||
readonly tasks = injectQuery(() =>
|
||||
this.#tasksService.allTasks(this.intervalMs()),
|
||||
)
|
||||
|
||||
readonly addMutation = injectMutation(() => this.#tasksService.addTask())
|
||||
readonly clearMutation = injectMutation(() =>
|
||||
this.#tasksService.clearAllTasks(),
|
||||
)
|
||||
|
||||
clearTasks() {
|
||||
this.clearMutation.mutate()
|
||||
}
|
||||
|
||||
inputChange($event: Event) {
|
||||
const target = $event.target as HTMLInputElement
|
||||
this.intervalMs.set(Number(target.value))
|
||||
}
|
||||
|
||||
addItem($event: Event) {
|
||||
const target = $event.target as HTMLInputElement
|
||||
const value = target.value
|
||||
this.addMutation.mutate(value)
|
||||
target.value = ''
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* MockApiInterceptor is used to simulate API responses for `/api/tasks` endpoints.
|
||||
* It handles the following operations:
|
||||
* - GET: Fetches all tasks from localStorage.
|
||||
* - POST: Adds a new task to localStorage.
|
||||
* - DELETE: Clears all tasks from localStorage.
|
||||
* Simulated responses include a delay to mimic network latency.
|
||||
*/
|
||||
import { HttpResponse } from '@angular/common/http'
|
||||
import { delay, of } from 'rxjs'
|
||||
import type {
|
||||
HttpEvent,
|
||||
HttpHandlerFn,
|
||||
HttpInterceptorFn,
|
||||
HttpRequest,
|
||||
} from '@angular/common/http'
|
||||
import type { Observable } from 'rxjs'
|
||||
|
||||
export const mockInterceptor: HttpInterceptorFn = (
|
||||
req: HttpRequest<unknown>,
|
||||
next: HttpHandlerFn,
|
||||
): Observable<HttpEvent<any>> => {
|
||||
const respondWith = (status: number, body: any) =>
|
||||
of(new HttpResponse({ status, body })).pipe(delay(100))
|
||||
if (req.url === '/api/tasks') {
|
||||
switch (req.method) {
|
||||
case 'GET':
|
||||
return respondWith(
|
||||
200,
|
||||
JSON.parse(localStorage.getItem('tasks') || '[]'),
|
||||
)
|
||||
case 'POST':
|
||||
const tasks = JSON.parse(localStorage.getItem('tasks') || '[]')
|
||||
tasks.push(req.body)
|
||||
localStorage.setItem('tasks', JSON.stringify(tasks))
|
||||
return respondWith(201, {
|
||||
status: 'success',
|
||||
task: req.body,
|
||||
})
|
||||
case 'DELETE':
|
||||
localStorage.removeItem('tasks')
|
||||
return respondWith(200, { status: 'success' })
|
||||
}
|
||||
}
|
||||
return next(req)
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { HttpClient } from '@angular/common/http'
|
||||
import { Injectable, inject } from '@angular/core'
|
||||
import {
|
||||
QueryClient,
|
||||
mutationOptions,
|
||||
queryOptions,
|
||||
} from '@tanstack/angular-query-experimental'
|
||||
|
||||
import { lastValueFrom } from 'rxjs'
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class TasksService {
|
||||
readonly #queryClient = inject(QueryClient) // Manages query state and caching
|
||||
readonly #http = inject(HttpClient) // Handles HTTP requests
|
||||
|
||||
/**
|
||||
* Fetches all tasks from the API.
|
||||
* Returns an observable containing an array of task strings.
|
||||
*/
|
||||
allTasks = (intervalMs: number) =>
|
||||
queryOptions({
|
||||
queryKey: ['tasks'],
|
||||
queryFn: () => {
|
||||
return lastValueFrom(this.#http.get<Array<string>>('/api/tasks'))
|
||||
},
|
||||
refetchInterval: intervalMs,
|
||||
})
|
||||
|
||||
/**
|
||||
* Creates a mutation for adding a task.
|
||||
* On success, invalidates and refetches the "tasks" query cache to update the task list.
|
||||
*/
|
||||
addTask() {
|
||||
return mutationOptions({
|
||||
mutationFn: (task: string) =>
|
||||
lastValueFrom(this.#http.post('/api/tasks', task)),
|
||||
mutationKey: ['tasks'],
|
||||
onSuccess: () => {
|
||||
this.#queryClient.invalidateQueries({ queryKey: ['tasks'] })
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a mutation for clearing all tasks.
|
||||
* On success, invalidates and refetches the "tasks" query cache to ensure consistency.
|
||||
*/
|
||||
clearAllTasks() {
|
||||
return mutationOptions({
|
||||
mutationFn: () => lastValueFrom(this.#http.delete('/api/tasks')),
|
||||
mutationKey: ['clearTasks'],
|
||||
onSuccess: () => {
|
||||
this.#queryClient.invalidateQueries({ queryKey: ['tasks'] })
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
BIN
examples/angular/auto-refetching/src/favicon.ico
Normal file
BIN
examples/angular/auto-refetching/src/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
13
examples/angular/auto-refetching/src/index.html
Normal file
13
examples/angular/auto-refetching/src/index.html
Normal file
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>TanStack Query Angular auto-refetching example</title>
|
||||
<base href="/" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="icon" type="image/x-icon" href="favicon.ico" />
|
||||
</head>
|
||||
<body>
|
||||
<app-root></app-root>
|
||||
</body>
|
||||
</html>
|
||||
13
examples/angular/auto-refetching/src/main.ts
Normal file
13
examples/angular/auto-refetching/src/main.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { bootstrapApplication } from '@angular/platform-browser'
|
||||
import { appConfig } from './app/app.config'
|
||||
import { AppComponent } from './app/app.component'
|
||||
|
||||
bootstrapApplication(AppComponent, appConfig)
|
||||
.then(() => {
|
||||
// an simple endpoint for getting current list
|
||||
localStorage.setItem(
|
||||
'tasks',
|
||||
JSON.stringify(['Item 1', 'Item 2', 'Item 3']),
|
||||
)
|
||||
})
|
||||
.catch((err) => console.error(err))
|
||||
9
examples/angular/auto-refetching/tsconfig.app.json
Normal file
9
examples/angular/auto-refetching/tsconfig.app.json
Normal file
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "./out-tsc/app",
|
||||
"types": []
|
||||
},
|
||||
"files": ["src/main.ts"],
|
||||
"include": ["src/**/*.d.ts"]
|
||||
}
|
||||
31
examples/angular/auto-refetching/tsconfig.json
Normal file
31
examples/angular/auto-refetching/tsconfig.json
Normal file
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"compileOnSave": false,
|
||||
"compilerOptions": {
|
||||
"outDir": "./dist/out-tsc",
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"strict": true,
|
||||
"noImplicitOverride": true,
|
||||
"noPropertyAccessFromIndexSignature": true,
|
||||
"noImplicitReturns": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"skipLibCheck": true,
|
||||
"isolatedModules": true,
|
||||
"esModuleInterop": true,
|
||||
"sourceMap": true,
|
||||
"declaration": false,
|
||||
"experimentalDecorators": true,
|
||||
"moduleResolution": "Bundler",
|
||||
"importHelpers": true,
|
||||
"target": "ES2022",
|
||||
"module": "ES2022",
|
||||
"useDefineForClassFields": false,
|
||||
"lib": ["ES2022", "dom"]
|
||||
},
|
||||
"angularCompilerOptions": {
|
||||
"enableI18nLegacyMessageIdFormat": false,
|
||||
"strictInjectionParameters": true,
|
||||
"strictInputAccessModifiers": true,
|
||||
"strictStandalone": true,
|
||||
"strictTemplates": true
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user