Skip to content

Commit

Permalink
Merge pull request #377 from surpise/fe/refactor/muation-hooks
Browse files Browse the repository at this point in the history
[FE] 컴포넌트에서 직접 호출하는 useMutation을 커스텀 훅으로 분리
  • Loading branch information
surpise authored Jan 22, 2024
2 parents cb95732 + cd2d8a9 commit dbbec4e
Show file tree
Hide file tree
Showing 20 changed files with 419 additions and 274 deletions.
46 changes: 15 additions & 31 deletions frontend/src/components/Common/DiaryListItem.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
import { useState, useEffect } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import EmojiPicker from 'emoji-picker-react';

import { postReaction, deleteReaction } from '@api/Reaction';

import { IDiaryContent } from '@type/components/Common/DiaryList';

import Reaction from '@components/Common/Reaction';
Expand All @@ -13,7 +10,8 @@ import ReactionList from '@components/Diary/ReactionList';
import Keyword from '@components/Common/Keyword';

import useModal from '@hooks/useModal';
import { useToast } from '@/hooks/useToast';
import usePostReactionMutation from '@hooks/usePostReactionMutation';
import useDeleteReactionMutation from '@hooks/useDeleteReactionMutation';

import { FEED, PAGE_URL } from '@util/constants';
import { formatDateString } from '@util/funcs';
Expand All @@ -24,44 +22,30 @@ interface DiaryListItemProps {
}

const DiaryListItem = ({ pageType, diaryItem }: DiaryListItemProps) => {
const queryClient = useQueryClient();
const navigate = useNavigate();
const openToast = useToast();
const [showEmojiPicker, setShowEmojiPicker] = useState(false);
const [selectedEmoji, setSelectedEmoji] = useState<string>('');
const [totalReaction, setTotalReaction] = useState(0);
const { isOpen, openModal } = useModal();

const userId = localStorage.getItem('userId') as string;

useEffect(() => {
setSelectedEmoji(diaryItem.leavedReaction);
setTotalReaction(diaryItem.reactionCount);
}, [diaryItem]);

const postReactionMutation = useMutation({
mutationFn: () => postReaction(Number(diaryItem.diaryId), selectedEmoji),
onSuccess: () => {
queryClient.removeQueries({
queryKey: ['dayDiaryList', localStorage.getItem('userId')],
});
queryClient.removeQueries({
queryKey: ['myDayDiaryList', localStorage.getItem('userId')],
});
openToast('공감을 남겼습니다!');
},
});

const deleteReactionMutation = useMutation({
mutationFn: () => deleteReaction(Number(diaryItem.diaryId), selectedEmoji),
onSuccess: () => {
queryClient.removeQueries({
queryKey: ['dayDiaryList', localStorage.getItem('userId')],
});
queryClient.removeQueries({
queryKey: ['myDayDiaryList', localStorage.getItem('userId')],
});
openToast('공감을 취소했습니다!');
},
});
const postReactionMutation = usePostReactionMutation(
Number(userId),
Number(diaryItem.diaryId),
selectedEmoji,
);

const deleteReactionMutation = useDeleteReactionMutation(
Number(userId),
Number(diaryItem.diaryId),
selectedEmoji,
);

const handleDeleteReaction = async () => {
await deleteReactionMutation.mutate();
Expand Down
36 changes: 5 additions & 31 deletions frontend/src/components/Detail/DiaryContent.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
import { useState, useEffect } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import EmojiPicker from 'emoji-picker-react';
import Parser from 'html-react-parser';

import { postReaction, deleteReaction } from '@api/Reaction';

import { IReactionedFriends } from '@type/components/Common/ReactionList';

import ProfileItem from '@components/Common/ProfileItem';
Expand All @@ -13,8 +10,9 @@ import Keyword from '@components/Common/Keyword';
import ReactionList from '@components/Diary/ReactionList';

import useModal from '@hooks/useModal';
import { useToast } from '@hooks/useToast';
import useReactionListQuery from '@hooks/useReactionListQuery';
import usePostReactionMutation from '@hooks/usePostReactionMutation';
import useDeleteReactionMutation from '@hooks/useDeleteReactionMutation';

import { formatDateString } from '@util/funcs';

Expand Down Expand Up @@ -45,40 +43,16 @@ const DiaryContent = ({
const [selectedEmoji, setSelectedEmoji] = useState('');
const [totalReaction, setTotalReaction] = useState(reactionCount);
const { openModal } = useModal();
const openToast = useToast();
const queryClient = useQueryClient();

const { data, isError, isSuccess } = useReactionListQuery(diaryId);

if (isError) {
return <p>Error fetching data</p>;
}

const postReactionMutation = useMutation({
mutationFn: () => postReaction(diaryId, selectedEmoji),
onSuccess: () => {
queryClient.removeQueries({
queryKey: ['dayDiaryList', localStorage.getItem('userId')],
});
queryClient.removeQueries({
queryKey: ['myDayDiaryList', localStorage.getItem('userId')],
});
openToast('공감을 남겼습니다!');
},
});

const deleteReactionMutation = useMutation({
mutationFn: () => deleteReaction(diaryId, selectedEmoji),
onSuccess: () => {
queryClient.removeQueries({
queryKey: ['dayDiaryList', localStorage.getItem('userId')],
});
queryClient.removeQueries({
queryKey: ['myDayDiaryList', localStorage.getItem('userId')],
});
openToast('공감을 취소했습니다!');
},
});
const postReactionMutation = usePostReactionMutation(userId, diaryId, selectedEmoji);

const deleteReactionMutation = useDeleteReactionMutation(userId, diaryId, selectedEmoji);

const handleDeleteReaction = async () => {
await deleteReactionMutation.mutate();
Expand Down
58 changes: 7 additions & 51 deletions frontend/src/components/Edit/KeywordBox.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
import { useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { useMutation, useQueryClient } from '@tanstack/react-query';

import { createDiary, updateDiary } from '@api/Edit';
import { useLocation } from 'react-router-dom';

import Loading from '@components/Common/Loading';
import Keyword from '@components/Common/Keyword';

import useEditStore from '@store/useEditStore';

import { useToast } from '@hooks/useToast';

import { PAGE_URL } from '@util/constants';
import useCreateDiaryMutation from '@hooks/useCreateDiaryMutation';
import useUpdateDiaryMutation from '@hooks/useUpdateDiaryMutation';

interface CreateDiaryParams {
title: string;
Expand All @@ -23,10 +20,9 @@ interface CreateDiaryParams {
}

const KeywordBox = () => {
const queryClient = useQueryClient();
const openToast = useToast();

const navigate = useNavigate();
const userId = localStorage.getItem('userid') as string;
const { state } = useLocation();
const [keyword, setKeyword] = useState<string>('');
const { diaryId, title, content, emoji, status, thumbnail, keywordList, setKeywordList } =
Expand All @@ -41,49 +37,9 @@ const KeywordBox = () => {
thumbnail,
};

const createDiaryMutation = useMutation({
mutationFn: (params: CreateDiaryParams) => createDiary(params),
onSuccess: () => {
navigate(PAGE_URL.MY_DIARY);
queryClient.invalidateQueries({
queryKey: ['grass', localStorage.getItem('userId')],
refetchType: 'all',
});
queryClient.invalidateQueries({
queryKey: ['emotionStat', localStorage.getItem('userId')],
refetchType: 'all',
});
queryClient.removeQueries({
queryKey: ['dayDiaryList', localStorage.getItem('userId')],
});
queryClient.removeQueries({
queryKey: ['myDayDiaryList', localStorage.getItem('userId')],
});
openToast('일기가 작성되었습니다!');
},
});

const updateDiaryMutation = useMutation({
mutationFn: (params: CreateDiaryParams) => updateDiary(params, diaryId),
onSuccess: () => {
navigate(`${PAGE_URL.DETAIL}/${diaryId}`);
queryClient.invalidateQueries({
queryKey: ['grass', localStorage.getItem('userId')],
refetchType: 'all',
});
queryClient.invalidateQueries({
queryKey: ['emotionStat', localStorage.getItem('userId')],
refetchType: 'all',
});
queryClient.removeQueries({
queryKey: ['dayDiaryList', localStorage.getItem('userId')],
});
queryClient.removeQueries({
queryKey: ['myDayDiaryList', localStorage.getItem('userId')],
});
openToast('일기가 수정되었습니다!');
},
});
const createDiaryMutation = useCreateDiaryMutation(userId);

const updateDiaryMutation = useUpdateDiaryMutation(userId, diaryId);

const onSubmit = () => {
if (!title || title.trim() === '' || !content || content.trim() === '') {
Expand Down
62 changes: 9 additions & 53 deletions frontend/src/components/Home/FriendModalItem.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { useNavigate } from 'react-router-dom';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useQueryClient } from '@tanstack/react-query';

import { cancelRequestFriend, deleteFriend, allowFriend, rejectFriend } from '@api/FriendModal';

import { useToast } from '@hooks/useToast';
import useCancelRequestMutation from '@hooks/useCancelRequestMutation';
import useDeleteFriendMutation from '@hooks/useDeleteFriendMutation';
import useAllowFriendMutation from '@hooks/useAllowFriendMutation';
import useRejectFriendMutation from '@hooks/useRejectFriendMutation';

import { PROFILE_BUTTON_TYPE, PAGE_URL, reactQueryKeys } from '@util/constants';

Expand All @@ -15,12 +16,9 @@ interface FriendModalItemProps {
type: string;
}

const DB_WAITING_TIME = 100;

const FriendModalItem = ({ email, profileImage, nickname, id, type }: FriendModalItemProps) => {
const navigate = useNavigate();
const queryClient = useQueryClient();
const openToast = useToast();

const goFriendHome = () => {
navigate(`${PAGE_URL.HOME}${id}`);
Expand All @@ -29,55 +27,13 @@ const FriendModalItem = ({ email, profileImage, nickname, id, type }: FriendModa
});
};

const cancelRequestMutation = useMutation({
mutationFn: (receiverId: number) => cancelRequestFriend(receiverId),
onSuccess() {
openToast('친구 신청을 취소했습니다.');
setTimeout(() => {
queryClient.invalidateQueries({
queryKey: [reactQueryKeys.SendList],
});
}, DB_WAITING_TIME);
},
});
const cancelRequestMutation = useCancelRequestMutation();

const deleteFriendMutation = useMutation({
mutationFn: (friendId: number) => deleteFriend(friendId),
onSuccess() {
openToast('친구가 삭제되었습니다.');
queryClient.invalidateQueries({
queryKey: [reactQueryKeys.FriendList],
});
queryClient.invalidateQueries({
queryKey: [reactQueryKeys.ProfileData],
});
},
});
const deleteFriendMutation = useDeleteFriendMutation();

const allowFriendMutation = useMutation({
mutationFn: (senderId: number) => allowFriend(senderId),
onSuccess() {
openToast('친구 요청을 수락하였습니다.');
queryClient.invalidateQueries({
queryKey: [reactQueryKeys.ReceivedList],
});
queryClient.invalidateQueries({
queryKey: [reactQueryKeys.ProfileData],
});
},
});
const allowFriendMutation = useAllowFriendMutation();

const rejectFriendMutation = useMutation({
mutationFn: (senderId: number) => rejectFriend(senderId),
onSuccess() {
openToast('친구 요청을 거절하였습니다.');
setTimeout(() => {
queryClient.invalidateQueries({
queryKey: [reactQueryKeys.ReceivedList],
});
}, DB_WAITING_TIME);
},
});
const rejectFriendMutation = useRejectFriendMutation();

const getButtonElement = (type: string) => {
switch (type) {
Expand Down
43 changes: 7 additions & 36 deletions frontend/src/components/Home/Profile.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,23 @@
import { useNavigate, useParams } from 'react-router-dom';
import { useMutation, useQueryClient } from '@tanstack/react-query';

import { deleteFriend, requestFriend } from '@api/FriendModal';

import Button from '@components/Common/Button';
import FriendList from '@components/Home/FriendList';
import FriendRequest from '@components/Home/FriendRequest';
import ProfileEdit from '@components/Home/ProfileEdit';

import useModal from '@hooks/useModal';
import useRequestFriendMutation from '@hooks/useRequestFriendMutation';
import useDeleteFriendMutation from '@hooks/useDeleteFriendMutation';

import {
DEFAULT,
GREET_MESSAGES,
PROFILE_MODAL_CONTENT_TYPE,
TEXT_ABOUT_EXISTED_TODAY,
LARGE,
PAGE_URL,
reactQueryKeys,
} from '@util/constants';

import { useToast } from '@hooks/useToast';
import useModal from '@hooks/useModal';

interface ProfileProps {
userId: number;
userData: ProfileData;
Expand All @@ -42,8 +39,6 @@ interface relationData {

const Profile = ({ userId, userData }: ProfileProps) => {
const navigate = useNavigate();
const queryClient = useQueryClient();
const openToast = useToast();

const loginUserId = localStorage.getItem('userId');
const paramsUserId = useParams().userId ?? false;
Expand All @@ -68,33 +63,9 @@ const Profile = ({ userId, userData }: ProfileProps) => {

const getRandomIndex = Math.floor(Math.random() * GREET_MESSAGES.length);

const requestFriendMutation = useMutation({
mutationFn: (receiverId: number) => requestFriend(receiverId),
onSuccess() {
openToast('친구 요청을 보냈습니다.');
setTimeout(() => {
queryClient.invalidateQueries({
queryKey: [reactQueryKeys.SendList],
});
queryClient.invalidateQueries({
queryKey: [reactQueryKeys.ProfileData],
});
}, 100);
},
});

const deleteFriendMutation = useMutation({
mutationFn: (friendId: number) => deleteFriend(friendId),
onSuccess() {
openToast('친구 삭제가 완료되었습니다.');
queryClient.invalidateQueries({
queryKey: [reactQueryKeys.FriendList],
});
queryClient.invalidateQueries({
queryKey: [reactQueryKeys.ProfileData],
});
},
});
const requestFriendMutation = useRequestFriendMutation();

const deleteFriendMutation = useDeleteFriendMutation();

const getRelationContent = () => {
if (relation === null) {
Expand Down
Loading

0 comments on commit dbbec4e

Please sign in to comment.