Skip to content

Commit

Permalink
refactor: 방 생성 및 방 참여 API 호출에 쓰로틀링을 걸어 중복 호출 방지 #401
Browse files Browse the repository at this point in the history
  • Loading branch information
rbgksqkr committed Nov 18, 2024
1 parent dbded16 commit 72b7be9
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
19 changes: 19 additions & 0 deletions frontend/src/hooks/useThrottle.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { useRef } from 'react';

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const useThrottle = (func: (...args: any[]) => void, delay = 1000) => {
const isThrottle = useRef(false);

// eslint-disable-next-line @typescript-eslint/no-explicit-any
return (...args: any[]) => {
if (!isThrottle.current) {
func(...args);
isThrottle.current = true;
setTimeout(() => {
isThrottle.current = false;
}, delay);
}
};
};

export default useThrottle;
14 changes: 12 additions & 2 deletions frontend/src/pages/NicknamePage/hooks/useMakeOrEnterRoom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { useNavigate, useParams } from 'react-router-dom';

import { enterRoom, createRoom } from '@/apis/room';
import { ROUTES } from '@/constants/routes';
import useThrottle from '@/hooks/useThrottle';
import { CreateOrEnterRoomResponse } from '@/types/room';
import { CustomError } from '@/utils/error';

Expand All @@ -22,6 +23,8 @@ const useMakeOrEnterRoom = () => {
},
});

const throttledCreateRoom = useThrottle(createRoomMutation.mutate);

const enterRoomMutation = useMutation<
CreateOrEnterRoomResponse,
CustomError,
Expand All @@ -33,12 +36,19 @@ const useMakeOrEnterRoom = () => {
},
});

const throttledEnterRoom = useThrottle(enterRoomMutation.mutate);

const handleMakeOrEnterRoom = () => {
const nickname = nicknameInputRef.current?.value || nicknameInputRef.current?.placeholder || '';

if (isMaster) {
createRoomMutation.mutate(nickname);
if (createRoomMutation.isPending) return;

throttledCreateRoom(nickname);
} else {
enterRoomMutation.mutate({ nickname, roomUuid: roomUuid || '' });
if (enterRoomMutation.isPending) return;

throttledEnterRoom({ nickname, roomUuid: roomUuid || '' });
}
};

Expand Down

0 comments on commit 72b7be9

Please sign in to comment.