Adding Realtime capabilities using socket
In this tutorial, we'll learn how to implement real-time messaging capabilities using MagicJS.
Last updated
In this tutorial, we'll learn how to implement real-time messaging capabilities using MagicJS.
Last updated
Create a new UI file named rt-message
within the main-features
folder and set its path to /
.
Add three buttons: Send Message, Leave Room, and Join Room.
Import Space
and Input
components, and wrap the buttons and input field within the Space
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.
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:
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 provided msg
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".
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.
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()
and socket.leaveRoom()
respectively in the frontend.
Refer the snippets below.
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.