Adding Realtime capabilities using socket
In this tutorial, we'll learn how to implement real-time messaging capabilities using MagicJS.
Setting Up UI
Create a new UI file named
rt-message
within themain-features
folder and set its path to/
.Add three buttons: Send Message, Leave Room, and Join Room.
Import
Space
andInput
components, and wrap the buttons and input field within theSpace
component.Add an input field and set the width of the input field to 300 for better usability.
Create a
div
with a height of 100 to display the last message.
State Management
Initialize two states to manage the last message and the input value.
Incorporate these states within the UI, ensuring their proper rendering and functionality.
Refer the code below:
Backend Configuration
Create a backend function named
send-msg
.Import
io
and emit a new message received from the frontend.
Refer the snippet below.
The function accepts a parameter
msg
of type string.Inside the function body:
It uses the
io
function to emit a message with the event name'new-message'
and the providedmsg
parameter.
Configure the frontend to call this function upon clicking the Send Message button, passing the input value and resetting it afterward.
Refer the snippet below.
Import the sendMsgServer
from "./send-msg.server".
Real-Time Messaging
Import
{ useSocket }
from'@magicjs.dev/frontend'
;Utilize the
useSocket()
hook to establish socket connection.Implement a
useEffect()
hook to subscribe to incoming messages and update the state accordingly.Ensure proper subscription management by unsubscribing within the hook.
Refer the snippet below.
Room Restriction
Modify the backend to emit messages only to a specific room, e.g., "secret-room".
Allow users to join and leave the room by invoking
socket.joinRoom()
andsocket.leaveRoom()
respectively in the frontend.
Refer the snippets below.
Testing
Open two browsers with the same page.
Test sending messages within the room, ensuring they are received in real-time only by members of the room.
🎉 Congratulations! You have successfully implemented real-time messaging capabilities using MagicJS's socket feature.
Last updated