From 744cb2cb2e9209ffba58bce625890e1900db0875 Mon Sep 17 00:00:00 2001 From: Wonsuk Choi Date: Thu, 29 Oct 2026 17:27:14 +0900 Subject: [PATCH] docs(examples/lit): add 'simple', 'basic-graphql-request', 'default-query-function', 'playground', 'algolia' and 'chat' examples (#12451) --- docs/config.json | 24 +++ examples/lit/algolia/README.md | 6 + examples/lit/algolia/eslint.config.js | 10 + examples/lit/algolia/index.html | 12 ++ examples/lit/algolia/package.json | 22 ++ examples/lit/algolia/src/main.ts | 33 +++ examples/lit/algolia/src/search-box.ts | 31 +++ examples/lit/algolia/src/search-results.ts | 107 ++++++++++ .../lit/algolia/src/services/products/api.ts | 27 +++ .../algolia/src/services/products/queries.ts | 33 +++ .../algolia/src/services/products/types.ts | 13 ++ examples/lit/algolia/src/styles.css | 59 +++++ examples/lit/algolia/src/vite-env.d.ts | 1 + examples/lit/algolia/tsconfig.json | 15 ++ examples/lit/basic-graphql-request/README.md | 6 + .../basic-graphql-request/eslint.config.js | 10 + examples/lit/basic-graphql-request/index.html | 12 ++ .../lit/basic-graphql-request/package.json | 23 ++ .../lit/basic-graphql-request/src/main.ts | 60 ++++++ .../basic-graphql-request/src/post-detail.ts | 51 +++++ .../basic-graphql-request/src/post-list.ts | 64 ++++++ .../src/services/posts/api.ts | 44 ++++ .../src/services/posts/queries.ts | 16 ++ .../src/services/posts/types.ts | 5 + .../lit/basic-graphql-request/tsconfig.json | 15 ++ examples/lit/chat/README.md | 6 + examples/lit/chat/eslint.config.js | 10 + examples/lit/chat/index.html | 12 ++ examples/lit/chat/package.json | 23 ++ examples/lit/chat/src/chat-message.ts | 42 ++++ examples/lit/chat/src/main.ts | 100 +++++++++ examples/lit/chat/src/message-bubble.ts | 37 ++++ .../lit/chat/src/services/messages/api.ts | 33 +++ .../lit/chat/src/services/messages/queries.ts | 17 ++ examples/lit/chat/src/style.css | 1 + examples/lit/chat/src/vite-env.d.ts | 1 + examples/lit/chat/tsconfig.json | 15 ++ examples/lit/chat/vite.config.ts | 6 + examples/lit/default-query-function/README.md | 6 + .../default-query-function/eslint.config.js | 10 + .../lit/default-query-function/index.html | 12 ++ .../lit/default-query-function/package.json | 21 ++ .../lit/default-query-function/src/main.ts | 77 +++++++ .../default-query-function/src/post-detail.ts | 53 +++++ .../default-query-function/src/post-list.ts | 65 ++++++ .../lit/default-query-function/src/types.ts | 5 + .../lit/default-query-function/tsconfig.json | 15 ++ examples/lit/playground/README.md | 6 + examples/lit/playground/eslint.config.js | 10 + examples/lit/playground/index.html | 12 ++ examples/lit/playground/package.json | 21 ++ examples/lit/playground/src/add-todo.ts | 58 +++++ examples/lit/playground/src/edit-todo.ts | 144 +++++++++++++ examples/lit/playground/src/main.ts | 202 ++++++++++++++++++ .../lit/playground/src/services/todos/api.ts | 117 ++++++++++ .../playground/src/services/todos/queries.ts | 28 +++ .../playground/src/services/todos/types.ts | 7 + examples/lit/playground/src/styles.css | 11 + examples/lit/playground/src/todo-list.ts | 90 ++++++++ examples/lit/playground/src/vite-env.d.ts | 1 + examples/lit/playground/tsconfig.json | 15 ++ examples/lit/simple/README.md | 6 + examples/lit/simple/eslint.config.js | 10 + examples/lit/simple/index.html | 12 ++ examples/lit/simple/package.json | 21 ++ examples/lit/simple/src/main.ts | 59 +++++ examples/lit/simple/src/services/repos/api.ts | 9 + .../lit/simple/src/services/repos/queries.ts | 11 + .../lit/simple/src/services/repos/types.ts | 7 + examples/lit/simple/tsconfig.json | 15 ++ pnpm-lock.yaml | 129 +++++++++++ 71 files changed, 2267 insertions(+) create mode 100644 examples/lit/algolia/README.md create mode 100644 examples/lit/algolia/eslint.config.js create mode 100644 examples/lit/algolia/index.html create mode 100644 examples/lit/algolia/package.json create mode 100644 examples/lit/algolia/src/main.ts create mode 100644 examples/lit/algolia/src/search-box.ts create mode 100644 examples/lit/algolia/src/search-results.ts create mode 100644 examples/lit/algolia/src/services/products/api.ts create mode 100644 examples/lit/algolia/src/services/products/queries.ts create mode 100644 examples/lit/algolia/src/services/products/types.ts create mode 100644 examples/lit/algolia/src/styles.css create mode 100644 examples/lit/algolia/src/vite-env.d.ts create mode 100644 examples/lit/algolia/tsconfig.json create mode 100644 examples/lit/basic-graphql-request/README.md create mode 100644 examples/lit/basic-graphql-request/eslint.config.js create mode 100644 examples/lit/basic-graphql-request/index.html create mode 100644 examples/lit/basic-graphql-request/package.json create mode 100644 examples/lit/basic-graphql-request/src/main.ts create mode 100644 examples/lit/basic-graphql-request/src/post-detail.ts create mode 100644 examples/lit/basic-graphql-request/src/post-list.ts create mode 100644 examples/lit/basic-graphql-request/src/services/posts/api.ts create mode 100644 examples/lit/basic-graphql-request/src/services/posts/queries.ts create mode 100644 examples/lit/basic-graphql-request/src/services/posts/types.ts create mode 100644 examples/lit/basic-graphql-request/tsconfig.json create mode 100644 examples/lit/chat/README.md create mode 100644 examples/lit/chat/eslint.config.js create mode 100644 examples/lit/chat/index.html create mode 100644 examples/lit/chat/package.json create mode 100644 examples/lit/chat/src/chat-message.ts create mode 100644 examples/lit/chat/src/main.ts create mode 100644 examples/lit/chat/src/message-bubble.ts create mode 100644 examples/lit/chat/src/services/messages/api.ts create mode 100644 examples/lit/chat/src/services/messages/queries.ts create mode 100644 examples/lit/chat/src/style.css create mode 100644 examples/lit/chat/src/vite-env.d.ts create mode 100644 examples/lit/chat/tsconfig.json create mode 100644 examples/lit/chat/vite.config.ts create mode 100644 examples/lit/default-query-function/README.md create mode 100644 examples/lit/default-query-function/eslint.config.js create mode 100644 examples/lit/default-query-function/index.html create mode 100644 examples/lit/default-query-function/package.json create mode 100644 examples/lit/default-query-function/src/main.ts create mode 100644 examples/lit/default-query-function/src/post-detail.ts create mode 100644 examples/lit/default-query-function/src/post-list.ts create mode 100644 examples/lit/default-query-function/src/types.ts create mode 100644 examples/lit/default-query-function/tsconfig.json create mode 100644 examples/lit/playground/README.md create mode 100644 examples/lit/playground/eslint.config.js create mode 100644 examples/lit/playground/index.html create mode 100644 examples/lit/playground/package.json create mode 100644 examples/lit/playground/src/add-todo.ts create mode 100644 examples/lit/playground/src/edit-todo.ts create mode 100644 examples/lit/playground/src/main.ts create mode 100644 examples/lit/playground/src/services/todos/api.ts create mode 100644 examples/lit/playground/src/services/todos/queries.ts create mode 100644 examples/lit/playground/src/services/todos/types.ts create mode 100644 examples/lit/playground/src/styles.css create mode 100644 examples/lit/playground/src/todo-list.ts create mode 100644 examples/lit/playground/src/vite-env.d.ts create mode 100644 examples/lit/playground/tsconfig.json create mode 100644 examples/lit/simple/README.md create mode 100644 examples/lit/simple/eslint.config.js create mode 100644 examples/lit/simple/index.html create mode 100644 examples/lit/simple/package.json create mode 100644 examples/lit/simple/src/main.ts create mode 100644 examples/lit/simple/src/services/repos/api.ts create mode 100644 examples/lit/simple/src/services/repos/queries.ts create mode 100644 examples/lit/simple/src/services/repos/types.ts create mode 100644 examples/lit/simple/tsconfig.json diff --git a/docs/config.json b/docs/config.json index 5865467d1f..10f04481ce 100644 --- a/docs/config.json +++ b/docs/config.json @@ -7100,6 +7100,30 @@ { "label": "SSR", "to": "framework/lit/examples/ssr" + }, + { + "label": "Simple", + "to": "framework/lit/examples/simple" + }, + { + "label": "Basic w/ GraphQL-Request", + "to": "framework/lit/examples/basic-graphql-request" + }, + { + "label": "Default Query Function", + "to": "framework/lit/examples/default-query-function" + }, + { + "label": "Playground", + "to": "framework/lit/examples/playground" + }, + { + "label": "Algolia", + "to": "framework/lit/examples/algolia" + }, + { + "label": "Chat example (streaming)", + "to": "framework/lit/examples/chat" } ] }, diff --git a/examples/lit/algolia/README.md b/examples/lit/algolia/README.md new file mode 100644 index 0000000000..dd443687fb --- /dev/null +++ b/examples/lit/algolia/README.md @@ -0,0 +1,6 @@ +# Algolia example + +To run this example: + +- `npm install` or `yarn` or `pnpm i` or `bun i` +- `npm run dev` or `yarn dev` or `pnpm dev` or `bun dev` diff --git a/examples/lit/algolia/eslint.config.js b/examples/lit/algolia/eslint.config.js new file mode 100644 index 0000000000..3a519b55ec --- /dev/null +++ b/examples/lit/algolia/eslint.config.js @@ -0,0 +1,10 @@ +// @ts-check + +import { tanstackConfig } from '@tanstack/eslint-config' +import pluginQuery from '@tanstack/eslint-plugin-query' +import { defineConfig } from 'eslint/config' + +export default defineConfig([ + ...tanstackConfig, + ...pluginQuery.configs['flat/recommended-strict'], +]) diff --git a/examples/lit/algolia/index.html b/examples/lit/algolia/index.html new file mode 100644 index 0000000000..227dc5e9a8 --- /dev/null +++ b/examples/lit/algolia/index.html @@ -0,0 +1,12 @@ + + + + + + TanStack Query Lit Algolia Example App + + + + + + diff --git a/examples/lit/algolia/package.json b/examples/lit/algolia/package.json new file mode 100644 index 0000000000..35059189da --- /dev/null +++ b/examples/lit/algolia/package.json @@ -0,0 +1,22 @@ +{ + "name": "@tanstack/query-example-lit-algolia", + "private": true, + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build", + "preview": "vite preview", + "test:eslint": "eslint ./src", + "test:types": "tsc --noEmit" + }, + "dependencies": { + "@algolia/client-search": "5.59.0", + "@tanstack/lit-query": "^0.2.31", + "lit": "^3.3.3" + }, + "devDependencies": { + "@tanstack/eslint-plugin-query": "^5.105.0", + "typescript": "^6.0.3", + "vite": "^8.3.5" + } +} diff --git a/examples/lit/algolia/src/main.ts b/examples/lit/algolia/src/main.ts new file mode 100644 index 0000000000..af752321a5 --- /dev/null +++ b/examples/lit/algolia/src/main.ts @@ -0,0 +1,33 @@ +import { LitElement, html } from 'lit' +import { QueryClient, QueryClientProvider } from '@tanstack/lit-query' +import './styles.css' +import './search-box' + +const queryClient = new QueryClient() + +class AlgoliaQueryProvider extends QueryClientProvider { + constructor() { + super() + this.client = queryClient + } +} + +class AlgoliaApp extends LitElement { + protected override createRenderRoot(): HTMLElement | DocumentFragment { + return this + } + + render() { + return html` + +
+

TanStack Query with Algolia

+ +
+
+ ` + } +} + +customElements.define('algolia-query-provider', AlgoliaQueryProvider) +customElements.define('algolia-app', AlgoliaApp) diff --git a/examples/lit/algolia/src/search-box.ts b/examples/lit/algolia/src/search-box.ts new file mode 100644 index 0000000000..ab68ca53d4 --- /dev/null +++ b/examples/lit/algolia/src/search-box.ts @@ -0,0 +1,31 @@ +import { LitElement, html } from 'lit' +import './search-results' + +class SearchBox extends LitElement { + static properties = { + query: { state: true }, + } + + private query = '' + + protected override createRenderRoot(): HTMLElement | DocumentFragment { + return this + } + + render() { + return html` +
+ + + (this.query = (event.currentTarget as HTMLInputElement).value)} + /> + +
+ ` + } +} + +customElements.define('search-box', SearchBox) diff --git a/examples/lit/algolia/src/search-results.ts b/examples/lit/algolia/src/search-results.ts new file mode 100644 index 0000000000..0bdd0b1f73 --- /dev/null +++ b/examples/lit/algolia/src/search-results.ts @@ -0,0 +1,107 @@ +import { LitElement, html } from 'lit' +import { createInfiniteQueryController } from '@tanstack/lit-query' +import { productsQueries } from './services/products/queries' + +type Product = { + name: string + shortDescription: string + salePrice: number +} + +class SearchResults extends LitElement { + static properties = { + query: { attribute: false }, + } + + query = '' + + private readonly products = createInfiniteQueryController(this, () => ({ + ...productsQueries.search({ + indexName: 'bestbuy', + query: this.query, + hitsPerPage: 5, + }), + select: (data) => data.pages.flatMap((page) => page.hits), + staleTime: 30 * 1000, // 30s + gcTime: 15 * 60 * 1000, // 15m + })) + + protected override createRenderRoot(): HTMLElement | DocumentFragment { + return this + } + + render() { + if (!this.query) return null + + const { + isLoading, + status, + error, + isFetching, + data: products, + hasNextPage, + isFetchingNextPage, + } = this.products() + + if (isLoading) return html`
Loading...
` + + if (status === 'error') return html`
Error: ${error.message}
` + + return html` +
+
+ Status: ${status} + ${isFetching ? html`fetching...` : null} +
+
+
+ ${ + products && products.length > 0 + ? products.map( + (product) => html` +
  • + ${product.name} + ${ + product.shortDescription + ? html` +
    + + ${product.shortDescription} + + ` + : null + } +
    + $${product.salePrice} +
  • + `, + ) + : html`

    No products found!

    ` + } +
    + ${ + hasNextPage + ? html` + + ` + : null + } + ${ + isFetchingNextPage + ? html`
    Fetching next page...
    ` + : null + } +
    +
    + ` + } +} + +customElements.define('search-results', SearchResults) diff --git a/examples/lit/algolia/src/services/products/api.ts b/examples/lit/algolia/src/services/products/api.ts new file mode 100644 index 0000000000..24ef6917b7 --- /dev/null +++ b/examples/lit/algolia/src/services/products/api.ts @@ -0,0 +1,27 @@ +import { searchClient } from '@algolia/client-search' +import type { SearchOptions, SearchResponse } from './types' + +// From Algolia example +// https://github.com/algolia/react-instantsearch +const ALGOLIA_APP_ID = 'latency' +const ALGOLIA_SEARCH_API_KEY = '6be0576ff61c053d5f9a3225e2a90f76' + +export const productsAPI = { + searchProducts: async ({ + indexName, + query, + pageParam, + hitsPerPage = 10, + }: SearchOptions): Promise> => { + const client = searchClient(ALGOLIA_APP_ID, ALGOLIA_SEARCH_API_KEY) + + console.log('algolia:search', { indexName, query, pageParam, hitsPerPage }) + + const { hits, nbPages = 0 } = await client.searchSingleIndex({ + indexName, + searchParams: { query, page: pageParam, hitsPerPage }, + }) + + return { hits, nbPages } + }, +} diff --git a/examples/lit/algolia/src/services/products/queries.ts b/examples/lit/algolia/src/services/products/queries.ts new file mode 100644 index 0000000000..26b7383854 --- /dev/null +++ b/examples/lit/algolia/src/services/products/queries.ts @@ -0,0 +1,33 @@ +import { infiniteQueryOptions, skipToken } from '@tanstack/lit-query' +import { productsAPI } from './api' +import type { SearchOptions } from './types' + +export const productsQueries = { + all: () => ['products'] as const, + search: ({ + indexName, + query, + hitsPerPage, + }: Omit) => + infiniteQueryOptions({ + queryKey: [ + ...productsQueries.all(), + 'search', + indexName, + query, + hitsPerPage, + ] as const, + queryFn: query + ? ({ pageParam }) => + productsAPI.searchProducts({ + indexName, + query, + pageParam, + hitsPerPage, + }) + : skipToken, + initialPageParam: 0, + getNextPageParam: (lastPage, _allPages, lastPageParam) => + lastPageParam + 1 < lastPage.nbPages ? lastPageParam + 1 : undefined, + }), +} diff --git a/examples/lit/algolia/src/services/products/types.ts b/examples/lit/algolia/src/services/products/types.ts new file mode 100644 index 0000000000..2749576ab2 --- /dev/null +++ b/examples/lit/algolia/src/services/products/types.ts @@ -0,0 +1,13 @@ +import type { Hit } from '@algolia/client-search' + +export type SearchOptions = { + indexName: string + query: string + pageParam: number + hitsPerPage: number +} + +export type SearchResponse = { + hits: Array> + nbPages: number +} diff --git a/examples/lit/algolia/src/styles.css b/examples/lit/algolia/src/styles.css new file mode 100644 index 0000000000..f38188db54 --- /dev/null +++ b/examples/lit/algolia/src/styles.css @@ -0,0 +1,59 @@ +.App { + font-family: sans-serif; + font-size: 14px; + padding: 20px; +} + +.loading { + padding-top: 20px; + padding-left: 20px; + color: darkmagenta; +} + +.search-status { + padding-top: 20px; + padding-left: 20px; + color: gray; +} + +.search-result { + padding-left: 20px; + padding-top: 20px; +} + +.search-more { + display: block; + margin-left: 20px; + margin-top: 20px; + padding: 0; + border: none; + background: none; + font: inherit; + color: blue; + cursor: pointer; + font-weight: bold; + text-transform: uppercase; +} + +.search-more:disabled { + color: gray; + cursor: default; +} + +.product { + padding-bottom: 5px; +} + +.product-name { + font-weight: bold; + font-size: 12px; +} + +.product-description { + font-size: 12px; +} + +.product-price { + font-size: 12px; + font-weight: bold; +} diff --git a/examples/lit/algolia/src/vite-env.d.ts b/examples/lit/algolia/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/lit/algolia/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/lit/algolia/tsconfig.json b/examples/lit/algolia/tsconfig.json new file mode 100644 index 0000000000..29bee299c6 --- /dev/null +++ b/examples/lit/algolia/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["ES2022", "DOM"], + "strict": true, + "noEmit": true, + "isolatedModules": true, + "skipLibCheck": true, + "allowJs": true, + "useDefineForClassFields": false + }, + "include": ["src/**/*.ts", "*.config.ts", "*.config.js"] +} diff --git a/examples/lit/basic-graphql-request/README.md b/examples/lit/basic-graphql-request/README.md new file mode 100644 index 0000000000..829e0bc937 --- /dev/null +++ b/examples/lit/basic-graphql-request/README.md @@ -0,0 +1,6 @@ +# Basic GraphQL Request example + +To run this example: + +- `npm install` or `yarn` or `pnpm i` or `bun i` +- `npm run dev` or `yarn dev` or `pnpm dev` or `bun dev` diff --git a/examples/lit/basic-graphql-request/eslint.config.js b/examples/lit/basic-graphql-request/eslint.config.js new file mode 100644 index 0000000000..3a519b55ec --- /dev/null +++ b/examples/lit/basic-graphql-request/eslint.config.js @@ -0,0 +1,10 @@ +// @ts-check + +import { tanstackConfig } from '@tanstack/eslint-config' +import pluginQuery from '@tanstack/eslint-plugin-query' +import { defineConfig } from 'eslint/config' + +export default defineConfig([ + ...tanstackConfig, + ...pluginQuery.configs['flat/recommended-strict'], +]) diff --git a/examples/lit/basic-graphql-request/index.html b/examples/lit/basic-graphql-request/index.html new file mode 100644 index 0000000000..91aadf2e72 --- /dev/null +++ b/examples/lit/basic-graphql-request/index.html @@ -0,0 +1,12 @@ + + + + + + TanStack Query Lit Basic GraphQL Request Example App + + + + + + diff --git a/examples/lit/basic-graphql-request/package.json b/examples/lit/basic-graphql-request/package.json new file mode 100644 index 0000000000..a5e001ded0 --- /dev/null +++ b/examples/lit/basic-graphql-request/package.json @@ -0,0 +1,23 @@ +{ + "name": "@tanstack/query-example-lit-basic-graphql-request", + "private": true, + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build", + "preview": "vite preview", + "test:eslint": "eslint ./src", + "test:types": "tsc --noEmit" + }, + "dependencies": { + "@tanstack/lit-query": "^0.2.31", + "graphql": "^16.9.0", + "graphql-request": "^7.1.2", + "lit": "^3.3.3" + }, + "devDependencies": { + "@tanstack/eslint-plugin-query": "^5.105.0", + "typescript": "^6.0.3", + "vite": "^8.3.5" + } +} diff --git a/examples/lit/basic-graphql-request/src/main.ts b/examples/lit/basic-graphql-request/src/main.ts new file mode 100644 index 0000000000..11b826fd70 --- /dev/null +++ b/examples/lit/basic-graphql-request/src/main.ts @@ -0,0 +1,60 @@ +import { LitElement, html } from 'lit' +import { QueryClient, QueryClientProvider } from '@tanstack/lit-query' +import './post-list' +import './post-detail' + +const queryClient = new QueryClient() + +class BasicGraphqlRequestQueryProvider extends QueryClientProvider { + constructor() { + super() + this.client = queryClient + } +} + +class BasicGraphqlRequestApp extends LitElement { + static properties = { + postId: { state: true }, + } + + private postId: string | null = null + + protected override createRenderRoot(): HTMLElement | DocumentFragment { + return this + } + + private setPostId(event: CustomEvent) { + this.postId = event.detail + } + + render() { + return html` + +

    + 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) + +

    + ${ + this.postId !== null + ? html`` + : html`` + } +
    + ` + } +} + +customElements.define( + 'basic-graphql-request-query-provider', + BasicGraphqlRequestQueryProvider, +) +customElements.define('basic-graphql-request-app', BasicGraphqlRequestApp) diff --git a/examples/lit/basic-graphql-request/src/post-detail.ts b/examples/lit/basic-graphql-request/src/post-detail.ts new file mode 100644 index 0000000000..cb6aff6bae --- /dev/null +++ b/examples/lit/basic-graphql-request/src/post-detail.ts @@ -0,0 +1,51 @@ +import { LitElement, html } from 'lit' +import { createQueryController } from '@tanstack/lit-query' +import { postsQueries } from './services/posts/queries' + +class PostDetail extends LitElement { + static properties = { + postId: { attribute: false }, + } + + postId = '' + + private readonly post = createQueryController(this, () => + postsQueries.detail(this.postId), + ) + + protected override createRenderRoot(): HTMLElement | DocumentFragment { + return this + } + + private back(event: Event) { + event.preventDefault() + this.dispatchEvent(new CustomEvent('set-post-id', { detail: null })) + } + + render() { + const { isPending, isError, isFetching, data, error } = this.post() + + return html` +
    +
    + Back +
    + ${ + isPending + ? html`
    Loading...
    ` + : isError + ? html`Error: ${error.message}` + : html` +

    ${data.title}

    +
    +

    ${data.body}

    +
    +
    ${isFetching ? 'Background Updating...' : ' '}
    + ` + } +
    + ` + } +} + +customElements.define('post-detail', PostDetail) diff --git a/examples/lit/basic-graphql-request/src/post-list.ts b/examples/lit/basic-graphql-request/src/post-list.ts new file mode 100644 index 0000000000..0ad9acb00d --- /dev/null +++ b/examples/lit/basic-graphql-request/src/post-list.ts @@ -0,0 +1,64 @@ +import { LitElement, html } from 'lit' +import { styleMap } from 'lit/directives/style-map.js' +import { createQueryController, useQueryClient } from '@tanstack/lit-query' +import { postsQueries } from './services/posts/queries' + +class PostList extends LitElement { + private readonly posts = createQueryController(this, postsQueries.list()) + + protected override createRenderRoot(): HTMLElement | DocumentFragment { + return this + } + + private setPostId(id: string) { + this.dispatchEvent(new CustomEvent('set-post-id', { detail: id })) + } + + render() { + const queryClient = useQueryClient() + const { isPending, isError, isFetching, data, error } = this.posts() + + return html` +
    +

    Posts

    +
    + ${ + isPending + ? html`
    Loading...
    ` + : isError + ? html`Error: ${error.message}` + : html` + +
    ${isFetching ? 'Background Updating...' : ' '}
    + ` + } +
    +
    + ` + } +} + +customElements.define('post-list', PostList) diff --git a/examples/lit/basic-graphql-request/src/services/posts/api.ts b/examples/lit/basic-graphql-request/src/services/posts/api.ts new file mode 100644 index 0000000000..764a820949 --- /dev/null +++ b/examples/lit/basic-graphql-request/src/services/posts/api.ts @@ -0,0 +1,44 @@ +import { gql, request } from 'graphql-request' +import type { Post } from './types' + +const endpoint = 'https://graphqlzero.almansi.me/api' + +export const postsAPI = { + getPosts: async (): Promise>> => { + const { + posts: { data }, + } = await request<{ + posts: { data: Array> } + }>( + endpoint, + gql` + query { + posts { + data { + id + title + } + } + } + `, + ) + return data + }, + getPost: async (postId: string): Promise => { + const { post } = await request<{ post: Post }>( + endpoint, + gql` + query Post($id: ID!) { + post(id: $id) { + id + title + body + } + } + `, + { id: postId }, + ) + + return post + }, +} diff --git a/examples/lit/basic-graphql-request/src/services/posts/queries.ts b/examples/lit/basic-graphql-request/src/services/posts/queries.ts new file mode 100644 index 0000000000..dbcda0d553 --- /dev/null +++ b/examples/lit/basic-graphql-request/src/services/posts/queries.ts @@ -0,0 +1,16 @@ +import { queryOptions } from '@tanstack/lit-query' +import { postsAPI } from './api' + +export const postsQueries = { + all: () => ['posts'] as const, + list: () => + queryOptions({ + queryKey: [...postsQueries.all(), 'list'] as const, + queryFn: () => postsAPI.getPosts(), + }), + detail: (postId: string) => + queryOptions({ + queryKey: [...postsQueries.all(), 'detail', postId] as const, + queryFn: () => postsAPI.getPost(postId), + }), +} diff --git a/examples/lit/basic-graphql-request/src/services/posts/types.ts b/examples/lit/basic-graphql-request/src/services/posts/types.ts new file mode 100644 index 0000000000..69eac73169 --- /dev/null +++ b/examples/lit/basic-graphql-request/src/services/posts/types.ts @@ -0,0 +1,5 @@ +export type Post = { + id: string + title: string + body: string +} diff --git a/examples/lit/basic-graphql-request/tsconfig.json b/examples/lit/basic-graphql-request/tsconfig.json new file mode 100644 index 0000000000..29bee299c6 --- /dev/null +++ b/examples/lit/basic-graphql-request/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["ES2022", "DOM"], + "strict": true, + "noEmit": true, + "isolatedModules": true, + "skipLibCheck": true, + "allowJs": true, + "useDefineForClassFields": false + }, + "include": ["src/**/*.ts", "*.config.ts", "*.config.js"] +} diff --git a/examples/lit/chat/README.md b/examples/lit/chat/README.md new file mode 100644 index 0000000000..f280b4c1c7 --- /dev/null +++ b/examples/lit/chat/README.md @@ -0,0 +1,6 @@ +# Chat example + +To run this example: + +- `npm install` or `yarn` or `pnpm i` or `bun i` +- `npm run dev` or `yarn dev` or `pnpm dev` or `bun dev` diff --git a/examples/lit/chat/eslint.config.js b/examples/lit/chat/eslint.config.js new file mode 100644 index 0000000000..3a519b55ec --- /dev/null +++ b/examples/lit/chat/eslint.config.js @@ -0,0 +1,10 @@ +// @ts-check + +import { tanstackConfig } from '@tanstack/eslint-config' +import pluginQuery from '@tanstack/eslint-plugin-query' +import { defineConfig } from 'eslint/config' + +export default defineConfig([ + ...tanstackConfig, + ...pluginQuery.configs['flat/recommended-strict'], +]) diff --git a/examples/lit/chat/index.html b/examples/lit/chat/index.html new file mode 100644 index 0000000000..37c3be5dd4 --- /dev/null +++ b/examples/lit/chat/index.html @@ -0,0 +1,12 @@ + + + + + + TanStack Query Lit Chat Example App + + + + + + diff --git a/examples/lit/chat/package.json b/examples/lit/chat/package.json new file mode 100644 index 0000000000..de4b95ee96 --- /dev/null +++ b/examples/lit/chat/package.json @@ -0,0 +1,23 @@ +{ + "name": "@tanstack/query-example-lit-chat", + "private": true, + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build", + "preview": "vite preview", + "test:eslint": "eslint ./src", + "test:types": "tsc --noEmit" + }, + "dependencies": { + "@tanstack/lit-query": "^0.2.31", + "lit": "^3.3.3" + }, + "devDependencies": { + "@tailwindcss/vite": "^4.3.3", + "@tanstack/eslint-plugin-query": "^5.105.0", + "tailwindcss": "^4.3.3", + "typescript": "^6.0.3", + "vite": "^8.3.5" + } +} diff --git a/examples/lit/chat/src/chat-message.ts b/examples/lit/chat/src/chat-message.ts new file mode 100644 index 0000000000..3ad6ffd952 --- /dev/null +++ b/examples/lit/chat/src/chat-message.ts @@ -0,0 +1,42 @@ +import { LitElement, html } from 'lit' +import { createQueryController } from '@tanstack/lit-query' +import { messagesQueries } from './services/messages/queries' +import './message-bubble' + +class ChatMessage extends LitElement { + static properties = { + messageId: { attribute: false }, + question: { attribute: false }, + } + + messageId = '' + question = '' + + private readonly message = createQueryController(this, () => + messagesQueries.detail(this.messageId, this.question), + ) + + protected override createRenderRoot(): HTMLElement | DocumentFragment { + return this + } + + render() { + const { error, data, isFetching } = this.message() + + if (error) return html`An error has occurred: ${error.message}` + + return html` +
    + + +
    + ` + } +} + +customElements.define('chat-message', ChatMessage) diff --git a/examples/lit/chat/src/main.ts b/examples/lit/chat/src/main.ts new file mode 100644 index 0000000000..3cb5c4321b --- /dev/null +++ b/examples/lit/chat/src/main.ts @@ -0,0 +1,100 @@ +import { LitElement, html } from 'lit' +import { repeat } from 'lit/directives/repeat.js' +import { QueryClient, QueryClientProvider } from '@tanstack/lit-query' +import './style.css' +import './chat-message' + +const queryClient = new QueryClient() + +class ChatQueryProvider extends QueryClientProvider { + constructor() { + super() + this.client = queryClient + } +} + +class ChatApp extends LitElement { + static properties = { + questions: { state: true }, + currentQuestion: { state: true }, + } + + private questions: Array<{ id: string; question: string }> = [] + private currentQuestion = '' + + protected override createRenderRoot(): HTMLElement | DocumentFragment { + return this + } + + private submitMessage(event: SubmitEvent) { + event.preventDefault() + this.questions = [ + ...this.questions, + { id: crypto.randomUUID(), question: this.currentQuestion }, + ] + this.currentQuestion = '' + } + + render() { + return html` + +
    +

    + TanStack Chat Example +

    +
    + ${repeat( + this.questions, + ({ id }) => id, + ({ id, question }) => + html``, + )} +
    +
    + + (this.currentQuestion = ( + event.currentTarget as HTMLInputElement + ).value)} + /> + +
    +
    +
    + ` + } +} + +customElements.define('chat-query-provider', ChatQueryProvider) +customElements.define('chat-app', ChatApp) diff --git a/examples/lit/chat/src/message-bubble.ts b/examples/lit/chat/src/message-bubble.ts new file mode 100644 index 0000000000..800c237850 --- /dev/null +++ b/examples/lit/chat/src/message-bubble.ts @@ -0,0 +1,37 @@ +import { LitElement, html } from 'lit' + +class MessageBubble extends LitElement { + static properties = { + inProgress: { attribute: false }, + message: { attribute: false }, + } + + inProgress = false + message = { content: '', isQuestion: false } + + protected override createRenderRoot(): HTMLElement | DocumentFragment { + return this + } + + render() { + return html` +
    +
    + ${this.message.content} ${this.inProgress ? '...' : null} +
    +
    + ` + } +} + +customElements.define('message-bubble', MessageBubble) diff --git a/examples/lit/chat/src/services/messages/api.ts b/examples/lit/chat/src/services/messages/api.ts new file mode 100644 index 0000000000..4a1f2c9457 --- /dev/null +++ b/examples/lit/chat/src/services/messages/api.ts @@ -0,0 +1,33 @@ +const answers = [ + "I'm just an example chat, I can't really answer any questions :(".split(' '), + 'TanStack is great. Would you like to know more?'.split(' '), +] + +export const messagesAPI = { + getAnswer: (_question: string, signal: AbortSignal) => { + return { + async *[Symbol.asyncIterator]() { + const answer = answers[Math.floor(Math.random() * answers.length)] + let index = 0 + while (index < answer.length) { + await new Promise((resolve) => { + const onAbort = () => { + clearTimeout(timeout) + resolve() + } + const timeout = setTimeout( + () => { + signal.removeEventListener('abort', onAbort) + resolve() + }, + 100 + Math.random() * 300, + ) + signal.addEventListener('abort', onAbort, { once: true }) + }) + if (signal.aborted) return + yield answer[index++] + } + }, + } + }, +} diff --git a/examples/lit/chat/src/services/messages/queries.ts b/examples/lit/chat/src/services/messages/queries.ts new file mode 100644 index 0000000000..725690a6d3 --- /dev/null +++ b/examples/lit/chat/src/services/messages/queries.ts @@ -0,0 +1,17 @@ +import { + queryOptions, + experimental_streamedQuery as streamedQuery, +} from '@tanstack/lit-query' +import { messagesAPI } from './api' + +export const messagesQueries = { + all: () => ['messages'] as const, + detail: (id: string, question: string) => + queryOptions({ + queryKey: [...messagesQueries.all(), 'detail', id, question] as const, + queryFn: streamedQuery({ + streamFn: ({ signal }) => messagesAPI.getAnswer(question, signal), + }), + staleTime: Infinity, + }), +} diff --git a/examples/lit/chat/src/style.css b/examples/lit/chat/src/style.css new file mode 100644 index 0000000000..d4b5078586 --- /dev/null +++ b/examples/lit/chat/src/style.css @@ -0,0 +1 @@ +@import 'tailwindcss'; diff --git a/examples/lit/chat/src/vite-env.d.ts b/examples/lit/chat/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/lit/chat/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/lit/chat/tsconfig.json b/examples/lit/chat/tsconfig.json new file mode 100644 index 0000000000..29bee299c6 --- /dev/null +++ b/examples/lit/chat/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["ES2022", "DOM"], + "strict": true, + "noEmit": true, + "isolatedModules": true, + "skipLibCheck": true, + "allowJs": true, + "useDefineForClassFields": false + }, + "include": ["src/**/*.ts", "*.config.ts", "*.config.js"] +} diff --git a/examples/lit/chat/vite.config.ts b/examples/lit/chat/vite.config.ts new file mode 100644 index 0000000000..fb0cdf00b5 --- /dev/null +++ b/examples/lit/chat/vite.config.ts @@ -0,0 +1,6 @@ +import { defineConfig } from 'vite' +import tailwindcss from '@tailwindcss/vite' + +export default defineConfig({ + plugins: [tailwindcss()], +}) diff --git a/examples/lit/default-query-function/README.md b/examples/lit/default-query-function/README.md new file mode 100644 index 0000000000..23fd50ded4 --- /dev/null +++ b/examples/lit/default-query-function/README.md @@ -0,0 +1,6 @@ +# Default Query Function example + +To run this example: + +- `npm install` or `yarn` or `pnpm i` or `bun i` +- `npm run dev` or `yarn dev` or `pnpm dev` or `bun dev` diff --git a/examples/lit/default-query-function/eslint.config.js b/examples/lit/default-query-function/eslint.config.js new file mode 100644 index 0000000000..81166d97c0 --- /dev/null +++ b/examples/lit/default-query-function/eslint.config.js @@ -0,0 +1,10 @@ +// @ts-check + +import { tanstackConfig } from '@tanstack/eslint-config' +import pluginQuery from '@tanstack/eslint-plugin-query' +import { defineConfig } from 'eslint/config' + +export default defineConfig([ + ...tanstackConfig, + ...pluginQuery.configs['flat/recommended'], +]) diff --git a/examples/lit/default-query-function/index.html b/examples/lit/default-query-function/index.html new file mode 100644 index 0000000000..cdbaf5d0fb --- /dev/null +++ b/examples/lit/default-query-function/index.html @@ -0,0 +1,12 @@ + + + + + + TanStack Query Lit Default Query Function Example App + + + + + + diff --git a/examples/lit/default-query-function/package.json b/examples/lit/default-query-function/package.json new file mode 100644 index 0000000000..0500578696 --- /dev/null +++ b/examples/lit/default-query-function/package.json @@ -0,0 +1,21 @@ +{ + "name": "@tanstack/query-example-lit-default-query-function", + "private": true, + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build", + "preview": "vite preview", + "test:eslint": "eslint ./src", + "test:types": "tsc --noEmit" + }, + "dependencies": { + "@tanstack/lit-query": "^0.2.31", + "lit": "^3.3.3" + }, + "devDependencies": { + "@tanstack/eslint-plugin-query": "^5.105.0", + "typescript": "^6.0.3", + "vite": "^8.3.5" + } +} diff --git a/examples/lit/default-query-function/src/main.ts b/examples/lit/default-query-function/src/main.ts new file mode 100644 index 0000000000..45281eed9b --- /dev/null +++ b/examples/lit/default-query-function/src/main.ts @@ -0,0 +1,77 @@ +import { LitElement, html } from 'lit' +import { QueryClient, QueryClientProvider } from '@tanstack/lit-query' +import './post-list' +import './post-detail' +import type { QueryKey } from '@tanstack/lit-query' + +// Define a default query function that will receive the query key +const defaultQueryFn = async ({ queryKey }: { queryKey: QueryKey }) => { + const response = await fetch( + `https://jsonplaceholder.typicode.com${queryKey[0]}`, + ) + if (!response.ok) throw new Error('Failed to fetch data') + return await response.json() +} + +// provide the default query function to your app with defaultOptions +const queryClient = new QueryClient({ + defaultOptions: { + queries: { + queryFn: defaultQueryFn, + }, + }, +}) + +class DefaultQueryFunctionQueryProvider extends QueryClientProvider { + constructor() { + super() + this.client = queryClient + } +} + +class DefaultQueryFunctionApp extends LitElement { + static properties = { + postId: { state: true }, + } + + private postId = -1 + + protected override createRenderRoot(): HTMLElement | DocumentFragment { + return this + } + + private setPostId(event: CustomEvent) { + this.postId = event.detail + } + + render() { + return html` + +

    + 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) + +

    + ${ + this.postId > -1 + ? html`` + : html`` + } +
    + ` + } +} + +customElements.define( + 'default-query-function-query-provider', + DefaultQueryFunctionQueryProvider, +) +customElements.define('default-query-function-app', DefaultQueryFunctionApp) diff --git a/examples/lit/default-query-function/src/post-detail.ts b/examples/lit/default-query-function/src/post-detail.ts new file mode 100644 index 0000000000..d4d4561d21 --- /dev/null +++ b/examples/lit/default-query-function/src/post-detail.ts @@ -0,0 +1,53 @@ +import { LitElement, html } from 'lit' +import { createQueryController } from '@tanstack/lit-query' +import type { Post } from './types' + +class PostDetail extends LitElement { + static properties = { + postId: { attribute: false }, + } + + postId = -1 + + // You can even leave out the queryFn and just go straight into options + private readonly post = createQueryController(this, () => ({ + queryKey: [`/posts/${this.postId}`], + enabled: !!this.postId, + })) + + protected override createRenderRoot(): HTMLElement | DocumentFragment { + return this + } + + private back(event: Event) { + event.preventDefault() + this.dispatchEvent(new CustomEvent('set-post-id', { detail: -1 })) + } + + render() { + const { isPending, isError, isFetching, data, error } = this.post() + + return html` +
    +
    + Back +
    + ${ + !this.postId || isPending + ? html`
    Loading...
    ` + : isError + ? html`Error: ${error.message}` + : html` +

    ${data.title}

    +
    +

    ${data.body}

    +
    +
    ${isFetching ? 'Background Updating...' : ' '}
    + ` + } +
    + ` + } +} + +customElements.define('post-detail', PostDetail) diff --git a/examples/lit/default-query-function/src/post-list.ts b/examples/lit/default-query-function/src/post-list.ts new file mode 100644 index 0000000000..3aa3b5ed98 --- /dev/null +++ b/examples/lit/default-query-function/src/post-list.ts @@ -0,0 +1,65 @@ +import { LitElement, html } from 'lit' +import { styleMap } from 'lit/directives/style-map.js' +import { createQueryController, useQueryClient } from '@tanstack/lit-query' +import type { Post } from './types' + +class PostList extends LitElement { + // All you have to do now is pass a key! + private readonly posts = createQueryController>(this, { + queryKey: ['/posts'], + }) + + protected override createRenderRoot(): HTMLElement | DocumentFragment { + return this + } + + private setPostId(id: number) { + this.dispatchEvent(new CustomEvent('set-post-id', { detail: id })) + } + + render() { + const queryClient = useQueryClient() + const { isPending, isError, isFetching, data, error } = this.posts() + + return html` +
    +

    Posts

    +
    + ${ + isPending + ? html`
    Loading...
    ` + : isError + ? html`Error: ${error.message}` + : html` + +
    ${isFetching ? 'Background Updating...' : ' '}
    + ` + } +
    +
    + ` + } +} + +customElements.define('post-list', PostList) diff --git a/examples/lit/default-query-function/src/types.ts b/examples/lit/default-query-function/src/types.ts new file mode 100644 index 0000000000..fb3835e9ff --- /dev/null +++ b/examples/lit/default-query-function/src/types.ts @@ -0,0 +1,5 @@ +export type Post = { + id: number + title: string + body: string +} diff --git a/examples/lit/default-query-function/tsconfig.json b/examples/lit/default-query-function/tsconfig.json new file mode 100644 index 0000000000..29bee299c6 --- /dev/null +++ b/examples/lit/default-query-function/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["ES2022", "DOM"], + "strict": true, + "noEmit": true, + "isolatedModules": true, + "skipLibCheck": true, + "allowJs": true, + "useDefineForClassFields": false + }, + "include": ["src/**/*.ts", "*.config.ts", "*.config.js"] +} diff --git a/examples/lit/playground/README.md b/examples/lit/playground/README.md new file mode 100644 index 0000000000..c75f082a87 --- /dev/null +++ b/examples/lit/playground/README.md @@ -0,0 +1,6 @@ +# Playground example + +To run this example: + +- `npm install` or `yarn` or `pnpm i` or `bun i` +- `npm run dev` or `yarn dev` or `pnpm dev` or `bun dev` diff --git a/examples/lit/playground/eslint.config.js b/examples/lit/playground/eslint.config.js new file mode 100644 index 0000000000..3a519b55ec --- /dev/null +++ b/examples/lit/playground/eslint.config.js @@ -0,0 +1,10 @@ +// @ts-check + +import { tanstackConfig } from '@tanstack/eslint-config' +import pluginQuery from '@tanstack/eslint-plugin-query' +import { defineConfig } from 'eslint/config' + +export default defineConfig([ + ...tanstackConfig, + ...pluginQuery.configs['flat/recommended-strict'], +]) diff --git a/examples/lit/playground/index.html b/examples/lit/playground/index.html new file mode 100644 index 0000000000..6f279e1c3f --- /dev/null +++ b/examples/lit/playground/index.html @@ -0,0 +1,12 @@ + + + + + + TanStack Query Lit Playground Example App + + + + + + diff --git a/examples/lit/playground/package.json b/examples/lit/playground/package.json new file mode 100644 index 0000000000..32094b0bcb --- /dev/null +++ b/examples/lit/playground/package.json @@ -0,0 +1,21 @@ +{ + "name": "@tanstack/query-example-lit-playground", + "private": true, + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build", + "preview": "vite preview", + "test:eslint": "eslint ./src", + "test:types": "tsc --noEmit" + }, + "dependencies": { + "@tanstack/lit-query": "^0.2.31", + "lit": "^3.3.3" + }, + "devDependencies": { + "@tanstack/eslint-plugin-query": "^5.105.0", + "typescript": "^6.0.3", + "vite": "^8.3.5" + } +} diff --git a/examples/lit/playground/src/add-todo.ts b/examples/lit/playground/src/add-todo.ts new file mode 100644 index 0000000000..2d63e60b7c --- /dev/null +++ b/examples/lit/playground/src/add-todo.ts @@ -0,0 +1,58 @@ +import { LitElement, html } from 'lit' +import { createMutationController } from '@tanstack/lit-query' +import { todosMutations, todosQueries } from './services/todos/queries' + +class AddTodo extends LitElement { + static properties = { + name: { state: true }, + } + + private name = '' + + private readonly addMutation = createMutationController(this, { + ...todosMutations.create(), + onSuccess: (_data, _variables, _onMutateResult, { client }) => { + client.invalidateQueries({ queryKey: todosQueries.lists() }) + }, + }) + + protected override createRenderRoot(): HTMLElement | DocumentFragment { + return this + } + + render() { + const { status, error, mutate } = this.addMutation() + + return html` +
    + + (this.name = (event.currentTarget as HTMLInputElement).value)} + /> + +
    + ${ + status === 'pending' + ? 'Saving...' + : status === 'error' + ? error.message + : status === 'success' + ? 'Saved!' + : null + } +
    +
    + ` + } +} + +customElements.define('add-todo', AddTodo) diff --git a/examples/lit/playground/src/edit-todo.ts b/examples/lit/playground/src/edit-todo.ts new file mode 100644 index 0000000000..6bc8079155 --- /dev/null +++ b/examples/lit/playground/src/edit-todo.ts @@ -0,0 +1,144 @@ +import { LitElement, html } from 'lit' +import { + createMutationController, + createQueryController, +} from '@tanstack/lit-query' +import { todosMutations, todosQueries } from './services/todos/queries' +import type { Todo } from './services/todos/types' + +class EditTodo extends LitElement { + static properties = { + editingIndex: { attribute: false }, + draft: { state: true }, + } + + editingIndex = 0 + private draft: Partial> = {} + + private readonly todo = createQueryController(this, () => + todosQueries.detail(this.editingIndex), + ) + + private readonly saveMutation = createMutationController(this, { + ...todosMutations.update(), + onSuccess: (todo, _variables, _onMutateResult, { client }) => { + // Update `todos` and the individual todo queries when this mutation succeeds + client.invalidateQueries({ queryKey: todosQueries.lists() }) + client.setQueryData(todosQueries.detail(this.editingIndex).queryKey, todo) + this.draft = {} + }, + }) + + protected override createRenderRoot(): HTMLElement | DocumentFragment { + return this + } + + private setEditingIndex(editingIndex: number | null) { + this.dispatchEvent( + new CustomEvent('set-editing-index', { detail: editingIndex }), + ) + } + + render() { + const { status, data, isFetching, failureCount, refetch } = this.todo() + const { + status: saveStatus, + error: saveError, + mutate: save, + } = this.saveMutation() + + const disableEditSave = status === 'pending' || saveStatus === 'pending' + + return html` +
    +
    + ${ + data + ? html` + + Editing Todo "${data.name}" (#${this.editingIndex}) + ` + : null + } +
    + ${ + status === 'pending' + ? html`Loading... (Attempt: ${failureCount + 1})` + : status === 'error' + ? html` + + Error! + + + ` + : html` + + +
    + +
    +
    + ${ + saveStatus === 'pending' + ? 'Saving...' + : saveStatus === 'error' + ? saveError.message + : saveStatus === 'success' + ? 'Saved!' + : null + } +
    +
    + ${ + isFetching + ? html` + Background Refreshing... (Attempt: + ${failureCount + 1}) + ` + : html` ` + } +
    + ` + } +
    + ` + } +} + +customElements.define('edit-todo', EditTodo) diff --git a/examples/lit/playground/src/main.ts b/examples/lit/playground/src/main.ts new file mode 100644 index 0000000000..e1100d1fc6 --- /dev/null +++ b/examples/lit/playground/src/main.ts @@ -0,0 +1,202 @@ +import { LitElement, html } from 'lit' +import { keyed } from 'lit/directives/keyed.js' +import { styleMap } from 'lit/directives/style-map.js' +import { QueryClient, QueryClientProvider } from '@tanstack/lit-query' +import './styles.css' +import { serverConfig } from './services/todos/api' +import './todo-list' +import './edit-todo' +import './add-todo' +import type { PropertyValues } from 'lit' + +const queryClient = new QueryClient() + +class PlaygroundQueryProvider extends QueryClientProvider { + constructor() { + super() + this.client = queryClient + } +} + +class PlaygroundApp extends LitElement { + static properties = { + staleTime: { state: true }, + gcTime: { state: true }, + localErrorRate: { state: true }, + localFetchTimeMin: { state: true }, + localFetchTimeMax: { state: true }, + editingIndex: { state: true }, + views: { state: true }, + } + + private staleTime = 1000 + private gcTime = 3000 + private localErrorRate = serverConfig.errorRate + private localFetchTimeMin = serverConfig.queryTimeMin + private localFetchTimeMax = serverConfig.queryTimeMax + private editingIndex: number | null = null + private views = ['', 'fruit', 'grape'] + + protected override createRenderRoot(): HTMLElement | DocumentFragment { + return this + } + + protected override willUpdate(changedProperties: PropertyValues) { + serverConfig.errorRate = this.localErrorRate + serverConfig.queryTimeMin = this.localFetchTimeMin + serverConfig.queryTimeMax = this.localFetchTimeMax + + if (changedProperties.has('staleTime') || changedProperties.has('gcTime')) { + queryClient.setDefaultOptions({ + queries: { + staleTime: this.staleTime, + gcTime: this.gcTime, + }, + }) + } + } + + private onNumberChange(event: Event, setValue: (value: number) => void) { + const value = (event.currentTarget as HTMLInputElement).valueAsNumber + if (!Number.isNaN(value)) { + setValue(value) + } + } + + private setEditingIndex(event: CustomEvent) { + this.editingIndex = event.detail + } + + render() { + return html` + +

    + The "staleTime" and "gcTime" durations have been altered in this + example to show how query stale-ness and query caching work on a + granular level +

    +
    + Stale Time: + + this.onNumberChange(event, (value) => (this.staleTime = value))} + /> +
    +
    + Garbage collection Time: + + this.onNumberChange(event, (value) => (this.gcTime = value))} + /> +
    +
    +
    + Error Rate: + + this.onNumberChange( + event, + (value) => (this.localErrorRate = value), + )} + /> +
    +
    + Fetch Time Min: + + this.onNumberChange( + event, + (value) => (this.localFetchTimeMin = value), + )} + /> +
    +
    + Fetch Time Max: + + this.onNumberChange( + event, + (value) => (this.localFetchTimeMax = value), + )} + /> +
    +
    +
    +
    + +
    +
    +
    + ${this.views.map( + (view) => html` +
    + +
    +
    + `, + )} + +
    + ${ + this.editingIndex !== null + ? html` + ${keyed( + this.editingIndex, + html``, + )} +
    + ` + : null + } + +
    +
    +
    + ` + } +} + +customElements.define('playground-query-provider', PlaygroundQueryProvider) +customElements.define('playground-app', PlaygroundApp) diff --git a/examples/lit/playground/src/services/todos/api.ts b/examples/lit/playground/src/services/todos/api.ts new file mode 100644 index 0000000000..5e83c3a531 --- /dev/null +++ b/examples/lit/playground/src/services/todos/api.ts @@ -0,0 +1,117 @@ +import type { Todo, Todos } from './types' + +let nextId = 0 +let list = [ + 'apple', + 'banana', + 'pineapple', + 'grapefruit', + 'dragonfruit', + 'grapes', +].map((d) => ({ id: nextId++, name: d, notes: 'These are some notes' })) + +export const serverConfig = { + errorRate: 0.05, + queryTimeMin: 1000, + queryTimeMax: 2000, +} + +export const todosAPI = { + getTodos: ({ + filter, + signal, + }: { + filter: string + signal: AbortSignal + }): Promise => { + console.info('getTodos', { filter }) + + signal.addEventListener('abort', () => { + console.info('cancelled', filter) + }) + + return new Promise((resolve, reject) => { + setTimeout( + () => { + if (Math.random() < serverConfig.errorRate) { + return reject( + new Error(JSON.stringify({ getTodos: { filter } }, null, 2)), + ) + } + resolve(list.filter((d) => d.name.includes(filter))) + }, + serverConfig.queryTimeMin + + Math.random() * + (serverConfig.queryTimeMax - serverConfig.queryTimeMin), + ) + }) + }, + getTodo: ({ id }: { id: number }): Promise => { + console.info('getTodo', { id }) + return new Promise((resolve, reject) => { + setTimeout( + () => { + if (Math.random() < serverConfig.errorRate) { + return reject( + new Error(JSON.stringify({ getTodo: { id } }, null, 2)), + ) + } + const todo = list.find((d) => d.id === id) + if (!todo) { + return reject(new Error(`Todo with id ${id} not found`)) + } + resolve(todo) + }, + serverConfig.queryTimeMin + + Math.random() * + (serverConfig.queryTimeMax - serverConfig.queryTimeMin), + ) + }) + }, + createTodo: ({ name, notes }: Omit): Promise => { + console.info('createTodo', { name, notes }) + return new Promise((resolve, reject) => { + setTimeout( + () => { + if (Math.random() < serverConfig.errorRate) { + return reject( + new Error( + JSON.stringify({ createTodo: { name, notes } }, null, 2), + ), + ) + } + const todo = { name, notes, id: nextId++ } + list = [...list, todo] + resolve(todo) + }, + serverConfig.queryTimeMin + + Math.random() * + (serverConfig.queryTimeMax - serverConfig.queryTimeMin), + ) + }) + }, + updateTodo: (todo: Todo): Promise => { + console.info('updateTodo', todo) + return new Promise((resolve, reject) => { + setTimeout( + () => { + if (Math.random() < serverConfig.errorRate) { + return reject( + new Error(JSON.stringify({ updateTodo: todo }, null, 2)), + ) + } + list = list.map((d) => { + if (d.id === todo.id) { + return todo + } + return d + }) + resolve(todo) + }, + serverConfig.queryTimeMin + + Math.random() * + (serverConfig.queryTimeMax - serverConfig.queryTimeMin), + ) + }) + }, +} diff --git a/examples/lit/playground/src/services/todos/queries.ts b/examples/lit/playground/src/services/todos/queries.ts new file mode 100644 index 0000000000..fb5f3965ef --- /dev/null +++ b/examples/lit/playground/src/services/todos/queries.ts @@ -0,0 +1,28 @@ +import { mutationOptions, queryOptions } from '@tanstack/lit-query' +import { todosAPI } from './api' + +export const todosQueries = { + all: () => ['todos'] as const, + lists: () => [...todosQueries.all(), 'list'] as const, + list: (filter: string) => + queryOptions({ + queryKey: [...todosQueries.lists(), { filter }] as const, + queryFn: ({ signal }) => todosAPI.getTodos({ filter, signal }), + }), + detail: (id: number) => + queryOptions({ + queryKey: [...todosQueries.all(), 'detail', id] as const, + queryFn: () => todosAPI.getTodo({ id }), + }), +} + +export const todosMutations = { + create: () => + mutationOptions({ + mutationFn: todosAPI.createTodo, + }), + update: () => + mutationOptions({ + mutationFn: todosAPI.updateTodo, + }), +} diff --git a/examples/lit/playground/src/services/todos/types.ts b/examples/lit/playground/src/services/todos/types.ts new file mode 100644 index 0000000000..ee0d9d1df5 --- /dev/null +++ b/examples/lit/playground/src/services/todos/types.ts @@ -0,0 +1,7 @@ +export type Todo = { + id: number + name: string + notes: string +} + +export type Todos = Array diff --git a/examples/lit/playground/src/styles.css b/examples/lit/playground/src/styles.css new file mode 100644 index 0000000000..eb0a265f1b --- /dev/null +++ b/examples/lit/playground/src/styles.css @@ -0,0 +1,11 @@ +body { + margin: 0; + padding: 1rem; + font-family: + -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', + 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + color: white; + background: #0b1521; +} diff --git a/examples/lit/playground/src/todo-list.ts b/examples/lit/playground/src/todo-list.ts new file mode 100644 index 0000000000..a2565d5fd9 --- /dev/null +++ b/examples/lit/playground/src/todo-list.ts @@ -0,0 +1,90 @@ +import { LitElement, html } from 'lit' +import { createQueryController } from '@tanstack/lit-query' +import { todosQueries } from './services/todos/queries' + +class TodoList extends LitElement { + static properties = { + initialFilter: { attribute: false }, + filter: { state: true }, + } + + initialFilter = '' + private filter: string | undefined + + private readonly todos = createQueryController(this, () => + todosQueries.list(this.filter ?? this.initialFilter), + ) + + protected override createRenderRoot(): HTMLElement | DocumentFragment { + return this + } + + private setEditingIndex(editingIndex: number | null) { + this.dispatchEvent( + new CustomEvent('set-editing-index', { detail: editingIndex }), + ) + } + + render() { + const { status, data, isFetching, error, failureCount, refetch } = + this.todos() + + return html` +
    +
    + +
    + ${ + status === 'pending' + ? html`Loading... (Attempt: ${failureCount + 1})` + : status === 'error' + ? html` + + Error: ${error.message} +
    + +
    + ` + : html` +
      + ${data.map( + (todo) => html` +
    • + ${todo.name} + +
    • + `, + )} +
    +
    + ${ + isFetching + ? html` + Background Refreshing... (Attempt: + ${failureCount + 1}) + ` + : html` ` + } +
    + ` + } +
    + ` + } +} + +customElements.define('todo-list', TodoList) diff --git a/examples/lit/playground/src/vite-env.d.ts b/examples/lit/playground/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/lit/playground/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/lit/playground/tsconfig.json b/examples/lit/playground/tsconfig.json new file mode 100644 index 0000000000..29bee299c6 --- /dev/null +++ b/examples/lit/playground/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["ES2022", "DOM"], + "strict": true, + "noEmit": true, + "isolatedModules": true, + "skipLibCheck": true, + "allowJs": true, + "useDefineForClassFields": false + }, + "include": ["src/**/*.ts", "*.config.ts", "*.config.js"] +} diff --git a/examples/lit/simple/README.md b/examples/lit/simple/README.md new file mode 100644 index 0000000000..01f1091919 --- /dev/null +++ b/examples/lit/simple/README.md @@ -0,0 +1,6 @@ +# Simple example + +To run this example: + +- `npm install` or `yarn` or `pnpm i` or `bun i` +- `npm run dev` or `yarn dev` or `pnpm dev` or `bun dev` diff --git a/examples/lit/simple/eslint.config.js b/examples/lit/simple/eslint.config.js new file mode 100644 index 0000000000..3a519b55ec --- /dev/null +++ b/examples/lit/simple/eslint.config.js @@ -0,0 +1,10 @@ +// @ts-check + +import { tanstackConfig } from '@tanstack/eslint-config' +import pluginQuery from '@tanstack/eslint-plugin-query' +import { defineConfig } from 'eslint/config' + +export default defineConfig([ + ...tanstackConfig, + ...pluginQuery.configs['flat/recommended-strict'], +]) diff --git a/examples/lit/simple/index.html b/examples/lit/simple/index.html new file mode 100644 index 0000000000..55e0e28f32 --- /dev/null +++ b/examples/lit/simple/index.html @@ -0,0 +1,12 @@ + + + + + + TanStack Query Lit Simple Example App + + + + + + diff --git a/examples/lit/simple/package.json b/examples/lit/simple/package.json new file mode 100644 index 0000000000..1f66af0803 --- /dev/null +++ b/examples/lit/simple/package.json @@ -0,0 +1,21 @@ +{ + "name": "@tanstack/query-example-lit-simple", + "private": true, + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build", + "preview": "vite preview", + "test:eslint": "eslint ./src", + "test:types": "tsc --noEmit" + }, + "dependencies": { + "@tanstack/lit-query": "^0.2.31", + "lit": "^3.3.3" + }, + "devDependencies": { + "@tanstack/eslint-plugin-query": "^5.105.0", + "typescript": "^6.0.3", + "vite": "^8.3.5" + } +} diff --git a/examples/lit/simple/src/main.ts b/examples/lit/simple/src/main.ts new file mode 100644 index 0000000000..f3451d0d16 --- /dev/null +++ b/examples/lit/simple/src/main.ts @@ -0,0 +1,59 @@ +import { LitElement, html } from 'lit' +import { + QueryClient, + QueryClientProvider, + createQueryController, +} from '@tanstack/lit-query' +import { reposQueries } from './services/repos/queries' + +const queryClient = new QueryClient() + +class SimpleQueryProvider extends QueryClientProvider { + constructor() { + super() + this.client = queryClient + } +} + +class SimpleExample extends LitElement { + private readonly repo = createQueryController(this, reposQueries.detail()) + + protected override createRenderRoot(): HTMLElement | DocumentFragment { + return this + } + + render() { + const { data, error, isFetching, isPending } = this.repo() + + if (isPending) return html`Loading...` + + if (error) return html`An error has occurred: ${error.message}` + + return html` +

    ${data.name}

    +

    ${data.description}

    + 👀 ${data.subscribers_count} + ✨ ${data.stargazers_count} + 🍴 ${data.forks_count} +
    ${isFetching ? 'Updating...' : ''}
    + ` + } +} + +class SimpleApp extends LitElement { + protected override createRenderRoot(): HTMLElement | DocumentFragment { + return this + } + + render() { + return html` + + + + ` + } +} + +customElements.define('simple-query-provider', SimpleQueryProvider) +customElements.define('simple-example', SimpleExample) +customElements.define('simple-app', SimpleApp) diff --git a/examples/lit/simple/src/services/repos/api.ts b/examples/lit/simple/src/services/repos/api.ts new file mode 100644 index 0000000000..90a79bc262 --- /dev/null +++ b/examples/lit/simple/src/services/repos/api.ts @@ -0,0 +1,9 @@ +import type { Repo } from './types' + +export const reposAPI = { + getRepo: async (): Promise => { + 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() + }, +} diff --git a/examples/lit/simple/src/services/repos/queries.ts b/examples/lit/simple/src/services/repos/queries.ts new file mode 100644 index 0000000000..f20ab78ff3 --- /dev/null +++ b/examples/lit/simple/src/services/repos/queries.ts @@ -0,0 +1,11 @@ +import { queryOptions } from '@tanstack/lit-query' +import { reposAPI } from './api' + +export const reposQueries = { + all: () => ['repos'] as const, + detail: () => + queryOptions({ + queryKey: [...reposQueries.all(), 'detail'] as const, + queryFn: () => reposAPI.getRepo(), + }), +} diff --git a/examples/lit/simple/src/services/repos/types.ts b/examples/lit/simple/src/services/repos/types.ts new file mode 100644 index 0000000000..a7a006f287 --- /dev/null +++ b/examples/lit/simple/src/services/repos/types.ts @@ -0,0 +1,7 @@ +export type Repo = { + name: string + description: string + subscribers_count: number + stargazers_count: number + forks_count: number +} diff --git a/examples/lit/simple/tsconfig.json b/examples/lit/simple/tsconfig.json new file mode 100644 index 0000000000..29bee299c6 --- /dev/null +++ b/examples/lit/simple/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["ES2022", "DOM"], + "strict": true, + "noEmit": true, + "isolatedModules": true, + "skipLibCheck": true, + "allowJs": true, + "useDefineForClassFields": false + }, + "include": ["src/**/*.ts", "*.config.ts", "*.config.js"] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a1f13054d4..1b8dd75de8 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -889,6 +889,28 @@ importers: specifier: 5.8.3 version: 5.8.3 + examples/lit/algolia: + dependencies: + '@algolia/client-search': + specifier: 5.59.0 + version: 5.59.0 + '@tanstack/lit-query': + specifier: ^0.2.31 + version: link:../../../packages/lit-query + lit: + specifier: ^3.3.3 + version: 3.3.3 + devDependencies: + '@tanstack/eslint-plugin-query': + specifier: ^5.105.0 + version: link:../../../packages/eslint-plugin-query + typescript: + specifier: ^6.0.3 + version: 6.0.3 + vite: + specifier: ^8.3.5 + version: 8.3.5(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.90.0)(terser@5.46.1)(tsx@4.21.0)(yaml@2.9.1) + examples/lit/basic: dependencies: '@tanstack/lit-query': @@ -908,6 +930,75 @@ importers: specifier: ^8.3.5 version: 8.3.5(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.90.0)(terser@5.46.1)(tsx@4.21.0)(yaml@2.9.0) + examples/lit/basic-graphql-request: + dependencies: + '@tanstack/lit-query': + specifier: ^0.2.31 + version: link:../../../packages/lit-query + graphql: + specifier: ^16.9.0 + version: 16.13.2 + graphql-request: + specifier: ^7.1.2 + version: 7.4.0(graphql@16.13.2) + lit: + specifier: ^3.3.3 + version: 3.3.3 + devDependencies: + '@tanstack/eslint-plugin-query': + specifier: ^5.105.0 + version: link:../../../packages/eslint-plugin-query + typescript: + specifier: ^6.0.3 + version: 6.0.3 + vite: + specifier: ^8.3.5 + version: 8.3.5(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.90.0)(terser@5.46.1)(tsx@4.21.0)(yaml@2.9.1) + + examples/lit/chat: + dependencies: + '@tanstack/lit-query': + specifier: ^0.2.31 + version: link:../../../packages/lit-query + lit: + specifier: ^3.3.3 + version: 3.3.3 + devDependencies: + '@tailwindcss/vite': + specifier: ^4.3.3 + version: 4.3.3(vite@8.3.5(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.90.0)(terser@5.46.1)(tsx@4.21.0)(yaml@2.9.1)) + '@tanstack/eslint-plugin-query': + specifier: ^5.105.0 + version: link:../../../packages/eslint-plugin-query + tailwindcss: + specifier: ^4.3.3 + version: 4.3.3 + typescript: + specifier: ^6.0.3 + version: 6.0.3 + vite: + specifier: ^8.3.5 + version: 8.3.5(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.90.0)(terser@5.46.1)(tsx@4.21.0)(yaml@2.9.1) + + examples/lit/default-query-function: + dependencies: + '@tanstack/lit-query': + specifier: ^0.2.31 + version: link:../../../packages/lit-query + lit: + specifier: ^3.3.3 + version: 3.3.3 + devDependencies: + '@tanstack/eslint-plugin-query': + specifier: ^5.105.0 + version: link:../../../packages/eslint-plugin-query + typescript: + specifier: ^6.0.3 + version: 6.0.3 + vite: + specifier: ^8.3.5 + version: 8.3.5(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.90.0)(terser@5.46.1)(tsx@4.21.0)(yaml@2.9.1) + examples/lit/pagination: dependencies: '@tanstack/lit-query': @@ -927,6 +1018,44 @@ importers: specifier: ^8.3.5 version: 8.3.5(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.90.0)(terser@5.46.1)(tsx@4.21.0)(yaml@2.9.0) + examples/lit/playground: + dependencies: + '@tanstack/lit-query': + specifier: ^0.2.31 + version: link:../../../packages/lit-query + lit: + specifier: ^3.3.3 + version: 3.3.3 + devDependencies: + '@tanstack/eslint-plugin-query': + specifier: ^5.105.0 + version: link:../../../packages/eslint-plugin-query + typescript: + specifier: ^6.0.3 + version: 6.0.3 + vite: + specifier: ^8.3.5 + version: 8.3.5(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.90.0)(terser@5.46.1)(tsx@4.21.0)(yaml@2.9.1) + + examples/lit/simple: + dependencies: + '@tanstack/lit-query': + specifier: ^0.2.31 + version: link:../../../packages/lit-query + lit: + specifier: ^3.3.3 + version: 3.3.3 + devDependencies: + '@tanstack/eslint-plugin-query': + specifier: ^5.105.0 + version: link:../../../packages/eslint-plugin-query + typescript: + specifier: ^6.0.3 + version: 6.0.3 + vite: + specifier: ^8.3.5 + version: 8.3.5(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.90.0)(terser@5.46.1)(tsx@4.21.0)(yaml@2.9.1) + examples/lit/ssr: dependencies: '@lit-labs/ssr':