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

[FE] feat: 리뷰 좋아요 디바운스 적용 #377

Merged
merged 4 commits into from
Aug 10, 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
1 change: 1 addition & 0 deletions frontend/.eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ module.exports = {
],
'import/no-unresolved': 'off',
'@typescript-eslint/no-empty-function': 'off',
'@typescript-eslint/ban-types': 'off',
},
settings: {
'import/resolver': {
Expand Down
34 changes: 21 additions & 13 deletions frontend/src/components/Review/ReviewItem/ReviewItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ import { useState } from 'react';
import styled from 'styled-components';

import { SvgIcon, TagList } from '@/components/Common';
import { useReviewFavorite } from '@/hooks/review';
import type { Review, ReviewFavoriteRequestBody } from '@/types/review';
import { useReviewFavoriteMutation } from '@/hooks/queries/review';
import useDebounce from '@/hooks/useDebounce';
import type { Review } from '@/types/review';
import { getRelativeDate } from '@/utils/relativeDate';

interface ReviewItemProps {
Expand All @@ -15,24 +16,31 @@ interface ReviewItemProps {
const srcPath = process.env.NODE_ENV === 'development' ? '' : '/images/';

const ReviewItem = ({ productId, review }: ReviewItemProps) => {
const { id, userName, profileImage, image, rating, tags, content, createdAt, rebuy, favoriteCount, favorite } = review;
const { id, userName, profileImage, image, rating, tags, content, createdAt, rebuy, favoriteCount, favorite } =
review;
const [isFavorite, setIsFavorite] = useState(favorite);
const [currentFavoriteCount, setCurrentFavoriteCount] = useState(favoriteCount);
const { request } = useReviewFavorite<ReviewFavoriteRequestBody>(productId, id);
const { mutate } = useReviewFavoriteMutation(productId, id);

const theme = useTheme();

const handleToggleFavorite = async () => {
try {
await request({ favorite: !isFavorite });

setIsFavorite((prev) => !prev);
setCurrentFavoriteCount((prev) => (isFavorite ? prev - 1 : prev + 1));
} catch (error) {
alert('리뷰 좋아요를 실패했습니다 🥲');
}
mutate(
{ favorite: !isFavorite },
{
onSuccess: () => {
setIsFavorite((prev) => !prev);
setCurrentFavoriteCount((prev) => (isFavorite ? prev - 1 : prev + 1));
},
onError: () => {
alert('리뷰 좋아요를 다시 시도해주세요.');
},
}
);
};

const [debouncedToggleFavorite] = useDebounce(handleToggleFavorite, 200);

return (
<ReviewItemContainer>
<ReviewerWrapper>
Expand Down Expand Up @@ -68,7 +76,7 @@ const ReviewItem = ({ productId, review }: ReviewItemProps) => {
<FavoriteButton
type="button"
variant="transparent"
onClick={handleToggleFavorite}
onClick={debouncedToggleFavorite}
aria-label={`좋아요 ${favoriteCount}개`}
>
<SvgIcon variant={isFavorite ? 'favoriteFilled' : 'favorite'} color={isFavorite ? 'red' : theme.colors.gray4} />
Expand Down
1 change: 1 addition & 0 deletions frontend/src/hooks/queries/review/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default as useReviewFavoriteMutation } from './useReviewFavoriteMutation';
18 changes: 18 additions & 0 deletions frontend/src/hooks/queries/review/useReviewFavoriteMutation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { useMutation } from '@tanstack/react-query';

import { productApi } from '@/apis';
import type { ReviewFavoriteRequestBody } from '@/types/review';

const headers = { 'Content-Type': 'application/json' };

const patchReviewFavorite = (productId: number, reviewId: number, body: ReviewFavoriteRequestBody) => {
return productApi.patch({ params: `/${productId}/reviews/${reviewId}`, credentials: true }, headers, body);
};

const useReviewFavoriteMutation = (productId: number, reviewId: number) => {
return useMutation({
mutationFn: (body: ReviewFavoriteRequestBody) => patchReviewFavorite(productId, reviewId, body),
});
};

export default useReviewFavoriteMutation;
34 changes: 34 additions & 0 deletions frontend/src/hooks/useDebounce.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { useCallback, useEffect, useRef } from 'react';

const useDebounce = (fn: Function, ms = 0) => {
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
const callbackRef = useRef(fn);

const debounce = useCallback(() => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}

timeoutRef.current = setTimeout(() => {
callbackRef.current();
}, ms);
}, [ms]);

const clear = useCallback(() => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
}, []);

useEffect(() => {
callbackRef.current = fn;
}, [fn]);

useEffect(() => {
return clear;
}, []);
Comment on lines +27 to +29
Copy link
Collaborator

Choose a reason for hiding this comment

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

clear만 따로 useEffect 선언해주는 이유는 뭔가요??

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

언마운트 될 때 타임아웃 클리어 하기 위해 작성했읍니다!


return [debounce, clear];
Copy link
Collaborator

Choose a reason for hiding this comment

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

순서 걱정 없는 객체로 리턴하는건 어떤가요?!

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

쓰는 곳에서 자유롭게 이름을 수정하기 위해 작성했습니다
{debounce: debouncedToggleFavorite} 이 형태가 너무 길어질거 같아서요

Copy link
Collaborator

Choose a reason for hiding this comment

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

ㅋㅋㅋㅋㅋ 알겠습니다

};

export default useDebounce;
Loading