useSocket()
useSocket function is like a walkie-talkie for websites, letting servers and clients chat back and forth in real-time.
Within the useSocket()
function, two functions are encapsulated.
joinRoom()
subscribe()
With joinRoom()
we can create a room for chats, games etc.
The
subscribe()
function acts as an event listener, fetching backend events upon occurrence. This enables the frontend to seamlessly display updates, eliminating the need for a page refresh—a functionality commonly exemplified in real-time messaging scenarios.
Frontend
This code establishes a WebSocket connection to the designated room (public/room)
and subscribes to a specific event (refresh)
. Upon the occurrence of this event, the handleFetchLatestMessage
function is invoked. To ensure proper cleanup, the component gracefully exits the room and unsubscribes from the event upon unmounting.
Backend
Here io().to(public/room).emit(refresh)
emits an event to the room 'public/room
' with the name 'refresh
' when the insertion of a new message into a MongoDB collection.
Last updated