본문으로 건너뛰기

쿼리 무효화

import { injectQuery, QueryClient } from '@tanstack/angular-query-experimental'

class QueryInvalidationExample {
queryClient = inject(QueryClient)

invalidateQueries() {
this.queryClient.invalidateQueries({ queryKey: ['todos'] })
}

// Both queries below will be invalidated
todoListQuery = injectQuery(() => ({
queryKey: ['todos'],
queryFn: fetchTodoList,
}))
todoListQuery = injectQuery(() => ({
queryKey: ['todos', { page: 1 }],
queryFn: fetchTodoList,
}))
}

invalidateQueries 메서드에 더 구체적인 쿼리 키를 전달하면 특정 변수가 있는 쿼리도 무효화할 수 있습니다:

queryClient.invalidateQueries({
queryKey: ['todos', { type: 'done' }],
})

// The query below will be invalidated
todoListQuery = injectQuery(() => ({
queryKey: ['todos', { type: 'done' }],
queryFn: fetchTodoList,
}))

// However, the following query below will NOT be invalidated
todoListQuery = injectQuery(() => ({
queryKey: ['todos'],
queryFn: fetchTodoList,
}))

invalidateQueries API는 매우 유연하므로, 변수나 하위 키가 더 이상 없는 todos 쿼리만**** 무효화하려는 경우에도 invalidateQueries 메서드에 exact: true 옵션을 전달할 수 있습니다:

queryClient.invalidateQueries({
queryKey: ['todos'],
exact: true,
})

// The query below will be invalidated
todoListQuery = injectQuery(() => ({
queryKey: ['todos'],
queryFn: fetchTodoList,
}))

// However, the following query below will NOT be invalidated
const todoListQuery = injectQuery(() => ({
queryKey: ['todos', { type: 'done' }],
queryFn: fetchTodoList,
}))

훨씬 더 세밀한 제어가 필요하다면 invalidateQueries 메서드에 predicate 함수를 전달할 수 있습니다. 이 함수는 쿼리 캐시의 각 Query 인스턴스를 전달받으며, 해당 쿼리를 무효화할지 여부에 따라 true 또는 false를 반환할 수 있습니다:

queryClient.invalidateQueries({
predicate: (query) =>
query.queryKey[0] === 'todos' && query.queryKey[1]?.version >= 10,
})

// The query below will be invalidated
todoListQuery = injectQuery(() => ({
queryKey: ['todos', { version: 20 }],
queryFn: fetchTodoList,
}))

// The query below will be invalidated
todoListQuery = injectQuery(() => ({
queryKey: ['todos', { version: 10 }],
queryFn: fetchTodoList,
}))

// However, the following query below will NOT be invalidated
todoListQuery = injectQuery(() => ({
queryKey: ['todos', { version: 5 }],
queryFn: fetchTodoList,
}))