Skip to content

Commit

Permalink
Fix: SocketToastProvider
Browse files Browse the repository at this point in the history
  • Loading branch information
14KGun committed May 1, 2023
1 parent 5e825fc commit df1d35e
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 72 deletions.
77 changes: 21 additions & 56 deletions src/components/Skeleton/SocketToastProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useEffect } from "react";
import { Socket, io } from "socket.io-client";
import { io } from "socket.io-client";

import { useValueRecoilState } from "hooks/useFetchRecoilState";

Expand All @@ -8,35 +8,32 @@ import { ioServer } from "loadenv";
export type SocketChatEventListner = (chats: Array<Chat>) => void;
export type SocketVoidEventListner = () => void;

let socket: Nullable<Socket> = null;

let isSocketReady: boolean = false;
let socketReadyQueue: Array<SocketVoidEventListner> = [];

let userId: Nullable<string> = null;
let reconnetTryCount: number = 0;
let initEventListener: Nullable<SocketChatEventListner> = null;
let reconnectEventListener: Nullable<SocketVoidEventListner> = null;
let pushBackEventListener: Nullable<SocketChatEventListner> = null;
let pushFrontEventListener: Nullable<SocketChatEventListner> = null;

// disconnect socket
const disconnectSocket = () => {
if (socket) socket.disconnect();
socket = null;
isSocketReady = false;
};

// connect socket with event listeners
const connectSocket = () => {
if (!userId) return;

disconnectSocket();
socket = io(ioServer, { withCredentials: true });
const SocketToastProvider = () => {
const { id: userId } = useValueRecoilState("loginInfo") || {};

socket.on("connect", () => {
if (!socket) return;
useEffect(() => {
if (!userId) return;
const socket = io(ioServer, { withCredentials: true });

socket.on("connect", () => {
isSocketReady = true;
socketReadyQueue.forEach((event) => event());
socketReadyQueue = [];
});
socket.on("disconnect", () => {
isSocketReady = false;
});
socket.io.on("reconnect", () => {
if (reconnectEventListener) reconnectEventListener();
});
socket.on("chat_init", ({ chats }) => {
if (initEventListener) initEventListener(chats);
});
Expand All @@ -47,43 +44,11 @@ const connectSocket = () => {
socket.on("chat_push_front", ({ chats }) => {
if (pushFrontEventListener) pushFrontEventListener(chats);
});
socket.on("health", (isHealth: boolean) => {
if (!socket) return null;
if (isHealth) {
isSocketReady = true;
socketReadyQueue.forEach((event) => event());
socketReadyQueue = [];
} else {
console.error("re-try connect with socket");
if (reconnetTryCount <= 10) {
reconnetTryCount += 1;
setTimeout(() => {
socket?.emit("health");
}, 500);
}
}
});
socket.on("disconnect", () => {
socket = null;
isSocketReady = false;
if (reconnectEventListener) socketReady(reconnectEventListener);
connectSocket();
});

socket.emit("health");
});
};

const SocketToastProvider = () => {
const { id: _userId } = useValueRecoilState("loginInfo") || {};

useEffect(() => {
userId = _userId;
if (userId) {
connectSocket();
return disconnectSocket;
}
}, [_userId]);
return () => {
socket.disconnect();
};
}, [userId]);

return null;
};
Expand Down
42 changes: 27 additions & 15 deletions src/pages/Chatting/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import Container from "./Container";
import Header from "./Header";
import MessageForm from "./MessageForm";
import MessagesBody from "./MessagesBody";
import { checkoutChat } from "./utils";
import { checkoutChat, getCleanupChats } from "./utils";

import alertAtom from "atoms/alert";
import { useSetRecoilState } from "recoil";
Expand Down Expand Up @@ -139,10 +139,6 @@ const Chatting = ({ roomId, layoutType }) => {
});
};

const sortChats = (chats) => {
return chats;
};

// socket event
useEffect(() => {
let isExpired = false;
Expand All @@ -157,27 +153,43 @@ const Chatting = ({ roomId, layoutType }) => {
if (isExpired) return;
sendingMessage.current = null;

setChats(sortChats(chats), () => {
setChats(getCleanupChats(chats), () => {
scrollToBottom();
callingInfScroll.current = false;
});
},
reconnectEventListener: () => {
reconnectListener: () => {
if (isExpired) return;
// axios({
// url: "/chats/load/after",
// method: "post",
// data: { roomId },
// });
setChats((prevChats) => {
axios({
url: "/chats/load/after",
method: "post",
data: {
roomId,
lastMsgDate: prevChats[prevChats.length - 1].time,
},
});
return prevChats;
});
},
pushBackListener: (chats) => {
if (isExpired) return;

const isMyMsg = chats.some((chat) => chat.authorId === userOid);
if (isMyMsg) sendingMessage.current = null;

if (chats.length > 10) {
axios({
url: "/chats/load/after",
method: "post",
data: {
roomId,
lastMsgDate: chats[chats.length - 1].time,
},
});
}
setChats(
(prevChats) => sortChats([...prevChats, ...chats]),
(prevChats) => getCleanupChats([...prevChats, ...chats]),
isMyMsg || isBottomOnScroll()
? () => scrollToBottom(true)
: () => setShowNewMessage(true)
Expand All @@ -191,7 +203,7 @@ const Chatting = ({ roomId, layoutType }) => {
return;
}
setChats((prevChats) =>
sortChats([...chats, checkoutChat, ...prevChats])
getCleanupChats([...chats, checkoutChat, ...prevChats])
);
},
});
Expand Down Expand Up @@ -292,7 +304,7 @@ const Chatting = ({ roomId, layoutType }) => {
recallEvent={fetchHeaderInfo}
/>
<MessagesBody
layoutType={layoutType} // fixme : is required?
layoutType={layoutType}
chats={chats}
forwardedRef={messagesBody}
handleScroll={handleScroll}
Expand Down
13 changes: 12 additions & 1 deletion src/pages/Chatting/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,16 @@ export const getChatUnquewKey = (chat: Chat): string => {
export const getCleanupChats = (
chats: Array<Chat | CheckoutChat>
): Array<Chat | CheckoutChat> => {
return [];
const newChats: Array<Chat | CheckoutChat> = [];
const keySet = new Set<string>();

chats.forEach((chat) => {
if (chat.type !== "inf-checkout") {
const key = getChatUnquewKey(chat as Chat);
if (keySet.has(key)) return;
keySet.add(key);
}
newChats.push(chat);
});
return newChats;
};

0 comments on commit df1d35e

Please sign in to comment.