Spaces:
Runtime error
Runtime error
File size: 2,297 Bytes
50ca514 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | import { SOCKET_HOST } from "@/lib/constants";
import { useAppStore } from "@/store";
import React, { createContext, useContext, useEffect, useRef } from "react";
import { io } from "socket.io-client";
const SocketContext = createContext(null);
export const useSocket = () => {
return useContext(SocketContext);
};
export const SocketProvider = ({ children }) => {
const socket = useRef();
const { userInfo } = useAppStore();
useEffect(() => {
if (userInfo) {
socket.current = io(SOCKET_HOST, {
withCredentials: true,
query: { userId: userInfo.id },
});
socket.current.on("connect", () => {
console.log("Connected to socket server");
});
const handleReceiveMessage = (message) => {
// Access the latest state values
const {
selectedChatData: currentChatData,
selectedChatType: currentChatType,
addMessage,
addContactInDMContacts,
} = useAppStore.getState();
if (
currentChatType !== undefined &&
(currentChatData._id === message.sender._id ||
currentChatData._id === message.recipient._id)
) {
addMessage(message);
}
addContactInDMContacts(message);
};
const handleReceiveChannelMessage = (message) => {
const {
selectedChatData,
selectedChatType,
addMessage,
addChannelInChannelLists,
} = useAppStore.getState();
if (
selectedChatType !== undefined &&
selectedChatData._id === message.channelId
) {
addMessage(message);
}
addChannelInChannelLists(message);
};
const addNewChannel = (channel) => {
const { addChannel } = useAppStore.getState();
addChannel(channel);
};
socket.current.on("receiveMessage", handleReceiveMessage);
socket.current.on("recieve-channel-message", handleReceiveChannelMessage);
socket.current.on("new-channel-added", addNewChannel);
return () => {
socket.current.disconnect();
};
}
}, [userInfo]);
return (
<SocketContext.Provider value={socket.current}>
{children}
</SocketContext.Provider>
);
};
export default SocketProvider;
|