Skip to content

Commit

Permalink
feat: (#563) 카테고리 즐겨찾기에 대한 낙관적 업데이트 구현 (#633)
Browse files Browse the repository at this point in the history
  • Loading branch information
inyeong-kang authored Sep 19, 2023
1 parent 604625e commit 854ea80
Showing 1 changed file with 23 additions and 3 deletions.
26 changes: 23 additions & 3 deletions frontend/src/hooks/query/category/useCategoryFavoriteToggle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,36 @@ import { QUERY_KEY } from '@constants/queryKey';

export const useCategoryFavoriteToggle = () => {
const queryClient = useQueryClient();
const LOGGED_IN = true;
const queryKey = [QUERY_KEY.CATEGORIES, LOGGED_IN];

const { mutate, isLoading, isError, error } = useMutation(
({ id, isFavorite }: Omit<Category, 'name'>) =>
isFavorite ? removeFavoriteCategory(id) : addFavoriteCategory(id),
{
onSuccess: () => {
queryClient.invalidateQueries([QUERY_KEY.CATEGORIES]);
onMutate: async ({ id }: Omit<Category, 'name'>) => {
const oldCategoryList: Category[] | undefined = queryClient.getQueryData(queryKey);

if (oldCategoryList) {
await queryClient.cancelQueries(queryKey);
const updatedCategoryList = oldCategoryList.map(item =>
item.id === id ? { ...item, isFavorite: !item.isFavorite } : item
);
queryClient.setQueryData(queryKey, updatedCategoryList);

return () => queryClient.setQueryData(queryKey, oldCategoryList);
}
},
onError: error => {
onError: (error, _, rollback) => {
if (rollback) {
rollback();
return;
}
window.console.log('Category favorite toggle error', error);
},
onSettled: () => {
queryClient.invalidateQueries(queryKey);
},
}
);

Expand Down

0 comments on commit 854ea80

Please sign in to comment.