useMutationState
useMutationState는 MutationCache의 모든 뮤테이션에 접근할 수 있게 해 주는 훅입니다. filters를 전달하여 뮤테이션의 범위를 좁히고, select를 전달하여 뮤테이션 상태를 변환할 수 있습니다.
예제 1: 실행 중인 모든 뮤테이션의 모든 변수 가져오기
import { useMutationState } from '@tanstack/react-query'
const variables = useMutationState({
filters: { status: 'pending' },
select: (mutation) => mutation.state.variables,
})
예제 2: mutationKey를 통해 특정 뮤테이션의 모든 데이터 가져오기
import { useMutation, useMutationState } from '@tanstack/react-query'
const mutationKey = ['posts']
// Some mutation that we want to get the state for
const mutation = useMutation({
mutationKey,
mutationFn: (newPost) => {
return axios.post('/posts', newPost)
},
})
const data = useMutationState({
// this mutation key needs to match the mutation key of the given mutation (see above)
filters: { mutationKey },
select: (mutation) => mutation.state.data,
})
예제 3: mutationKey를 통해 최신 뮤테이션 데이터에 접근하기.
mutate를 호출할 때마다 gcTime밀리초 동안 뮤테이션 캐시에 새 항목이 추가됩니다.
가장 최근 호출에 접근하려면 useMutationState가 반환하는 마지막 항목을 확인할 수 있습니다.
import { useMutation, useMutationState } from '@tanstack/react-query'
const mutationKey = ['posts']
// Some mutation that we want to get the state for
const mutation = useMutation({
mutationKey,
mutationFn: (newPost) => {
return axios.post('/posts', newPost)
},
})
const data = useMutationState({
// this mutation key needs to match the mutation key of the given mutation (see above)
filters: { mutationKey },
select: (mutation) => mutation.state.data,
})
// Latest mutation data
const latest = data[data.length - 1]
옵션
optionsfilters?: MutationFilters: 뮤테이션 필터select?: (mutation: Mutation) => TResult- 뮤테이션 상태를 변환하는 데 사용합니다.
queryClient?: QueryClient- 사용자 지정 QueryClient를 사용하려면 이를 사용합니다. 그렇지 않으면 가장 가까운 context의 항목이 사용됩니다.
반환값
Array<TResult>- 일치하는 각 뮤테이션에 대해
select가 반환하는 값으로 구성된 Array입니다.
- 일치하는 각 뮤테이션에 대해