Dependant Query
userId 값이 있을 때만 실행되도록 설정
const { data: user } = useQuery({
queryKey: ['user', email],
queryFn: getUserByEmail,
});
const userId = user?.id
const {
data: projects,
} = useQuery({
queryKey: ['projects', userId],
queryFn: getProjectsByUser,
enabled: !!userId,
});
Paginated Query
const {data: postsData } = useQuery({
queryKey: ['posts', page],
queryFn: () => getPosts(page, PAGE_LIMIT),
placeholderData: keepPreviousData,
});
useEffect(() => {
if (!isPlaceholderData && postsData?.hasMore) {
queryClient.prefetchQuery({
queryKey: ['posts', page + 1],
queryFn: () => getPosts(page + 1, PAGE_LIMIT),
});
}
}, [isPlaceholderData, postsData, queryClient, page]);
Infinite Query
const {
data: postsData,
isPending,
isError,
hasNextPage,
fetchNextPage,
isFetchingNextPage,
} = useInfiniteQuery({
queryKey: ['posts'],
queryFn: ({ pageParam }) => getPosts(pageParam, LIMIT),
initialPageParam: 0,
getNextPageParam: (lastPage, allPages, lastPageParam, allPageParams) =>
lastPage.hasMore ? lastPageParam + 1 : undefined,
});
Optimistic Updates
const likeMutation = useMutation({
mutationFn: async ({ postId, username, userAction }) => {
if (userAction === USER_ACTION.LIKE_POST) {
await likePost(postId, username);
} else {
await unlikePost(postId, username);
}
},
onMutate: async ({ postId, username, userAction }) => {
await queryClient.cancelQueries({
queryKey: [QUERY_KEYS.LIKE_STATUS, postId],
});
await queryClient.cancelQueries({
queryKey: [QUERY_KEYS.NUM_OF_LIKES, postId],
});
const prevLikeStatus = queryClient.getQueryData([
QUERY_KEYS.LIKE_STATUS,
postId,
username,
]);
const prevLikeCount = queryClient.getQueryData([
QUERY_KEYS.LIKE_COUNT,
postId,
]);
queryClient.setQueryData(
[QUERY_KEYS.LIKE_STATUS, postId, username],
() => userAction === USER_ACTION.LIKE_POST
);
queryClient.setQueryData([QUERY_KEYS.LIKE_COUNT, postId], (prev) => {
userAction === USER_ACTION.LIKE_POST ? prev + 1 : prev - 1;
});
return { prevLikeStatus, prevLikeCount };
},
onError: (err, { postId, username }, context) => {
queryClient.setQueryData(
[QUERY_KEYS.LIKE_STATUS, postId, username],
context.prevLikeStatus
);
queryClient.setQueryData(
[QUERY_KEYS.LIKE_COUNT, postId],
context.prevLikeCount
);
},
onSettled: (data, err, { postId, username }) => {
queryClient.invalidateQueries({
queryKey: [QUERY_KEYS.LIKE_STATUS, postId, username],
});
queryClient.invalidateQueries({
queryKey: [QUERY_KEYS.LIKE_COUNT, postId],
});
},
});