Skip to content

Commit

Permalink
[fix]: react auth fix
Browse files Browse the repository at this point in the history
  • Loading branch information
VictoryJu committed Oct 28, 2024
1 parent 9bcb6ae commit 174a450
Show file tree
Hide file tree
Showing 7 changed files with 77 additions and 18 deletions.
24 changes: 24 additions & 0 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,18 @@ import { RootRouter } from './router/RootRouter';
import { setUserAuth } from './stores/useAuthStore';
import { showiOSInfo } from './webview/utils';

const AUTH_UPDATE_EVENT = 'authUpdate';

if (!window.handleIosWebviewToken) {
window.handleIosWebviewToken = (token, uuid) => {
showiOSInfo(`token:${token},uuid:${uuid}`);
if (token) {
setUserAuth(token, uuid);
window.dispatchEvent(
new CustomEvent(AUTH_UPDATE_EVENT, {
detail: { token, uuid },
})
);
return 'success';
}
return 'fail';
Expand All @@ -16,9 +23,26 @@ if (!window.handleIosWebviewToken) {

function App() {
useEffect(() => {
const handleAuthUpdate = (event: CustomEvent) => {
const { token, uuid } = event.detail;
console.log('Auth updated:', token, uuid);
};

window.addEventListener(
AUTH_UPDATE_EVENT,
handleAuthUpdate as EventListener
);

if (window.webkit?.messageHandlers.webviewInit) {
window.webkit.messageHandlers.webviewInit.postMessage('webviewReady');
}

return () => {
window.removeEventListener(
AUTH_UPDATE_EVENT,
handleAuthUpdate as EventListener
);
};
}, []);
return <RootRouter />;
}
Expand Down
5 changes: 4 additions & 1 deletion src/components/Chat/ChatRooms/ChatRooms.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { useNavigate } from 'react-router';
import { useChatRooms } from '@/hooks/api/useChat';
import ChatRoomsEdit from '../ChatRoomsEdit/ChatRoomsEdit';
import ChatItemBase from './ChatItemBase/ChatItemBase';
import { useAuthStore } from '@/stores/useAuthStore';

const ChatRooms = () => {
const [isEdit, setIsEdit] = useState(false);
Expand All @@ -13,7 +14,9 @@ const ChatRooms = () => {
setIsEdit((prev) => !prev);
};

const { data: chatRoomsData } = useChatRooms();
const token = useAuthStore((state) => state.accessToken);

const { data: chatRoomsData } = useChatRooms(token);

const navigate = useNavigate();

Expand Down
4 changes: 1 addition & 3 deletions src/hooks/api/useChat.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import { useQuery, useSuspenseQuery } from '@tanstack/react-query';
import { fetchChatRoomMessages, fetchChatRooms } from './services/chat';
import { ReqChatRoomMessages } from './types/chat';
import { useAuthStore } from '@/stores/useAuthStore';
import { chatKeys } from './keys/chat';

export const useChatRooms = () => {
const token = useAuthStore((state) => state.accessToken);
export const useChatRooms = (token: string) => {
return useSuspenseQuery({
queryKey: ['chatRooms', token],
queryFn: () => {
Expand Down
2 changes: 1 addition & 1 deletion src/hooks/socket/useSocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export const useSocket = () => {
ackTimeout: MAX_ACK_TIME,
retries: INITIAL_RETRY,
withCredentials: true,
transports: ['websocket', 'polling'],
transports: ['websocket'],
});
}, [token]);

Expand Down
51 changes: 42 additions & 9 deletions src/hooks/useChat.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useState } from 'react';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useChatRoomMessages } from './api/useChat';
import { ChatMessage } from './api/types/chat';
import { useSocket } from './socket/useSocket';
Expand All @@ -13,13 +13,19 @@ export const useChat = (chatRoomId: string) => {
const { data: previousMessages } = useChatRoomMessages({
chatRoomId,
});
console.log(previousMessages);
const [messages, setMessages] = useState<ChatMessage[]>(
previousMessages?.data || []
);

const [messages, setMessages] = useState<ChatMessage[]>([]);

const hasSetupListeners = useRef(false);

useEffect(() => {
if (previousMessages?.data) {
setMessages(previousMessages.data);
}
}, [previousMessages]);

useEffect(() => {
if (!socket || !chatRoomId) return;
if (!socket || !chatRoomId || hasSetupListeners.current) return;

const joinRoom = () => {
if (chatRoomId) {
Expand All @@ -35,13 +41,25 @@ export const useChat = (chatRoomId: string) => {

const handleReceiveMessage = (msg: ChatMessage) => {
console.log(msg);
setMessages((prevMessages) => [...prevMessages, msg]);
setMessages((prevMessages) => {
// 중복 메시지 방지
const isDuplicate = prevMessages.some(
(prevMsg) => prevMsg.chatMessageId === msg.chatMessageId
);
if (isDuplicate) return prevMessages;
return [...prevMessages, msg];
});
};
socket.off('connect', handleConnect);
socket.off('receive', handleReceiveMessage);
socket.off('exception');

socket.on('connect', handleConnect);
socket.on('receive', handleReceiveMessage);
socket.on('exception', (message) => console.log('Exception:', message));

hasSetupListeners.current = true;

if (socket.connected) {
joinRoom();
}
Expand All @@ -50,14 +68,29 @@ export const useChat = (chatRoomId: string) => {
socket.off('connect', handleConnect);
socket.off('receive', handleReceiveMessage);
socket.off('exception');
hasSetupListeners.current = false;
};
}, [socket, chatRoomId]);

const sendMessage = useCallback(
(message: object) => {
if (socket && socket.connected && message) {
if (!socket?.connected || !message) return;

// 메시지 전송 중 상태 관리
let isProcessing = false;

if (isProcessing) return;

try {
isProcessing = true;
console.log('sendMessage', message);
socket.emit('send', message);
socket.emit('send', message, () => {
// 서버로부터 응답을 받으면 처리 완료
isProcessing = false;
});
} catch (error) {
console.error('Failed to send message:', error);
isProcessing = false;
}
},
[socket]
Expand Down
3 changes: 1 addition & 2 deletions src/pages/Chat/ChatRoom/ChatRoom.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@ import styles from './ChatRoom.module.scss';
import ArrowLeftTailIcon from '@/icons/icon/ArrowLeftTail';
import DotsVerticalIcon from '@/icons/icon/DotsVertical';
import { useLocation, useNavigate } from 'react-router';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useEffect, useRef, useState } from 'react';
import { useAuthStore } from '@/stores/useAuthStore';
import { UploadIcon, CameraIcon } from '@/icons/icon';
import { useChat } from '@/hooks/useChat';
import { useChatRoomMessages } from '@/hooks/api/useChat';
import ChatMessage from '@/components/Chat/ChatRoom/ChatMessage';

type ChatMessageType = 'TEXT' | 'IMAGE' | 'VIDEO';
Expand Down
6 changes: 4 additions & 2 deletions src/stores/useAuthStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@ import { persist } from 'zustand/middleware';
interface IAuthStore {
accessToken: string;
uuid: string;
setAuth: (token: string, uuid: string) => void;
}

export const useAuthStore = create(
persist<IAuthStore>(
() => ({
(set) => ({
accessToken: '',
uuid: '',
setAuth: (token, uuid) => set({ accessToken: token, uuid }),
}),
{
name: 'auth-storage',
Expand All @@ -19,6 +21,6 @@ export const useAuthStore = create(
);

export const setUserAuth = (accessToken: string, uuid: string) =>
useAuthStore.setState({ accessToken, uuid });
useAuthStore.getState().setAuth(accessToken, uuid);

export const logout = useAuthStore.persist.clearStorage;

0 comments on commit 174a450

Please sign in to comment.