Skip to content

Commit

Permalink
add socket event listeners for user management and clean-up
Browse files Browse the repository at this point in the history
  • Loading branch information
deveshidwivedi committed Jun 20, 2024
1 parent 58b9e04 commit b20ae4c
Showing 1 changed file with 30 additions and 1 deletion.
31 changes: 30 additions & 1 deletion modules/room/context/Room.context.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { socket } from "@/common/lib/socket";
import usersAtom, { useUserIds } from "@/common/recoil/users";
import { MotionValue, useMotionValue } from "framer-motion";
import { createContext, ReactChild } from "react";
import { createContext, ReactChild, useEffect } from "react";
import { useSet } from "react-use";
import { useSetRecoilState } from "recoil";

//creating context for x & y coordinates
export const roomContext = createContext<{
Expand All @@ -9,8 +13,33 @@ export const roomContext = createContext<{

const RoomContextProvider = ({ children }: { children: ReactChild }) => {

const setUsers= useSetRecoilState(usersAtom);
const usersIds= useUserIds();
const x = useMotionValue(0);
const y = useMotionValue(0);

// socket events for user join/leave and clean up listeners
useEffect(()=> {
socket.on("users_in_room", (newUsers)=>{
newUsers.forEach((user)=> {
if(!usersIds.includes(user) && user !== socket.id){
setUsers((prevUsers)=> ({...prevUsers, [user]:[] }));
}

});
});
socket.on("user_disconnected", (userId)=> {
setUsers((prevUsers)=> {
const newUsers= {...prevUsers};
delete newUsers[userId];
return newUsers;
});
});
return () => {
socket.off("users_in_room");
socket.off("user_disconnected");
};
}, [setUsers, usersIds]);
//motion values to context consumers
return (
<roomContext.Provider value={{ x, y }}>
Expand Down

0 comments on commit b20ae4c

Please sign in to comment.