Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

카테고리 즐겨찾기에 대한 낙관적 업데이트 구현 #633

Merged
merged 1 commit into from
Sep 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

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);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

마지막에 return () => 해주는 것은 무엇을 뜻하나요?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

onError의 rollback() 으로 쓰일 콜백함수를 지칭합니다~!

}
},
onError: error => {
onError: (error, _, rollback) => {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍👍👍

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

Expand Down
Loading