并行查询
并行查询是指同时运行的查询,这样 UI 就不必等待一个请求完成后再启动下一个请求。
手动并行查询
当查询数量固定时,在同一宿主(host)上创建多个查询控制器。所有控制器都会在宿主连接时自动订阅。
TypeScript
1import { LitElement, html } from 'lit'2import { createQueryController } from '@tanstack/lit-query'3 4class DashboardView extends LitElement {5 private readonly users = createQueryController(this, {6 queryKey: ['users'],7 queryFn: fetchUsers,8 })9 10 private readonly teams = createQueryController(this, {11 queryKey: ['teams'],12 queryFn: fetchTeams,13 })14 15 private readonly projects = createQueryController(this, {16 queryKey: ['projects'],17 queryFn: fetchProjects,18 })19 20 render() {21 const users = this.users()22 const teams = this.teams()23 const projects = this.projects()24 25 if (users.isPending || teams.isPending || projects.isPending) {26 return html`Loading...`27 }28 29 if (users.isError || teams.isError || projects.isError) {30 return html`Unable to load dashboard`31 }32 33 return html`34 <dashboard-summary35 .users=${users.data}36 .teams=${teams.data}37 .projects=${projects.data}38 ></dashboard-summary>39 `40 }41}每个控制器接收相同的 ReactiveControllerHost。若未显式传入 QueryClient,则每个控制器会解析离其最近的已连接 QueryClientProvider。
动态并行查询
当查询数量随宿主状态变化时,请使用 createQueriesController。它接受一个 queries 数组,并返回一个用于访问查询结果数组的访问器(accessor)。
若查询列表依赖于响应式宿主字段,请使用选项获取器(options getter):
TypeScript
1import { LitElement, html } from 'lit'2import { createQueriesController } from '@tanstack/lit-query'3 4class UsersDetails extends LitElement {5 static properties = {6 userIds: { attribute: false },7 }8 9 userIds: Array<string> = []10 11 private readonly users = createQueriesController(this, () => ({12 queries: this.userIds.map((id) => ({13 queryKey: ['user', id],14 queryFn: () => fetchUserById(id),15 })),16 }))17 18 render() {19 const userQueries = this.users()20 21 return html`22 <ul>23 ${userQueries.map((query, index) => {24 if (query.isPending) return html`<li>Loading...</li>`25 if (query.isError) return html`<li>Error loading user</li>`2627 return html`<li>${this.userIds[index]}: ${query.data.name}</li>`28 })}29 </ul>30 `31 }32}结果的顺序与输入查询的顺序一致。
合并结果
当组件需要一个派生值而非查询结果数组时,请使用 combine:
TypeScript
1private readonly dashboard = createQueriesController(this, {2 queries: [3 { queryKey: ['stats'], queryFn: fetchStats },4 { queryKey: ['projects'], queryFn: fetchProjects },5 ],6 combine: ([stats, projects]) => ({7 activeUsers: stats.data?.activeUsers ?? 0,8 projects: projects.data ?? [],9 isPending: stats.isPending || projects.isPending,10 isError: stats.isError || projects.isError,11 }),12})TypeScript
1render() {2 const dashboard = this.dashboard()3 4 if (dashboard.isPending) return html`Loading...`5 if (dashboard.isError) return html`Unable to load dashboard`6 7 return html`8 <p>Total projects: ${dashboard.projects.length}</p>9 <p>Active users: ${dashboard.activeUsers}</p>10 `11}若 queries 数组中多次出现相同的查询键,这些条目将共享缓存数据。如果每个渲染行都需要独立的查询状态,请先对重复的查询键进行去重。