본문으로 건너뛰기

병렬 쿼리

병렬 쿼리는 동시에 실행되는 쿼리이므로 UI는 다음 요청을 시작하기 전에 한 요청이 완료되기를 기다리지 않습니다.

수동 병렬 쿼리

쿼리 수가 고정되어 있으면 동일한 호스트에 여러 쿼리 컨트롤러를 생성합니다. 호스트가 연결되면 모두 구독합니다.

import { LitElement, html } from 'lit'
import { createQueryController } from '@tanstack/lit-query'

class DashboardView extends LitElement {
private readonly users = createQueryController(this, {
queryKey: ['users'],
queryFn: fetchUsers,
})

private readonly teams = createQueryController(this, {
queryKey: ['teams'],
queryFn: fetchTeams,
})

private readonly projects = createQueryController(this, {
queryKey: ['projects'],
queryFn: fetchProjects,
})

render() {
const users = this.users()
const teams = this.teams()
const projects = this.projects()

if (users.isPending || teams.isPending || projects.isPending) {
return html`Loading...`
}

if (users.isError || teams.isError || projects.isError) {
return html`Unable to load dashboard`
}

return html`
<dashboard-summary
.users=${users.data}
.teams=${teams.data}
.projects=${projects.data}
></dashboard-summary>
`
}
}

각 컨트롤러는 동일한 ReactiveControllerHost를 받습니다. 명시적인 QueryClient가 전달되지 않으면 각 컨트롤러는 연결된 가장 가까운 QueryClientProvider를 이행합니다.

동적 병렬 쿼리

호스트 상태에 따라 쿼리 수가 변경되면 createQueriesController를 사용하세요. 이 함수는 queries 배열을 받아 쿼리 결과 배열의 accessor를 반환합니다.

쿼리 목록이 반응형 호스트 필드에 종속되는 경우 options getter를 사용합니다:

import { LitElement, html } from 'lit'
import { createQueriesController } from '@tanstack/lit-query'

class UsersDetails extends LitElement {
static properties = {
userIds: { attribute: false },
}

userIds: Array<string> = []

private readonly users = createQueriesController(this, () => ({
queries: this.userIds.map((id) => ({
queryKey: ['user', id],
queryFn: () => fetchUserById(id),
})),
}))

render() {
const userQueries = this.users()

return html`
<ul>
${userQueries.map((query, index) => {
if (query.isPending) return html`<li>Loading...</li>`
if (query.isError) return html`<li>Error loading user</li>`

return html`<li>${this.userIds[index]}: ${query.data.name}</li>`
})}
</ul>
`
}
}

결과의 순서는 입력 쿼리의 순서와 일치합니다.

결과 결합

컴포넌트가 쿼리 결과 배열 대신 하나의 파생 값을 원할 때 combine을 사용합니다:

private readonly dashboard = createQueriesController(this, {
queries: [
{ queryKey: ['stats'], queryFn: fetchStats },
{ queryKey: ['projects'], queryFn: fetchProjects },
],
combine: ([stats, projects]) => ({
activeUsers: stats.data?.activeUsers ?? 0,
projects: projects.data ?? [],
isPending: stats.isPending || projects.isPending,
isError: stats.isError || projects.isError,
}),
})
render() {
const dashboard = this.dashboard()

if (dashboard.isPending) return html`Loading...`
if (dashboard.isError) return html`Unable to load dashboard`

return html`
<p>Total projects: ${dashboard.projects.length}</p>
<p>Active users: ${dashboard.activeUsers}</p>
`
}

queries 배열에 동일한 쿼리 키가 두 번 이상 있으면 해당 항목들이 캐시된 데이터를 공유할 수 있습니다. 렌더링된 각 행에 독립적인 쿼리 상태가 필요하다면 먼저 반복되는 키를 중복 제거하세요.