Adding Realtime capabilities using socket

In this tutorial, we'll learn how to implement real-time messaging capabilities using MagicJS.

Add Realtime Capabilities

Setting Up UI

  1. Create a new UI file named rt-message within the main-features folder and set its path to /.

  2. Add three buttons: Send Message, Leave Room, and Join Room.

  3. Import Space and Input components, and wrap the buttons and input field within the Space component.

  4. Add an input field and set the width of the input field to 300 for better usability.

  5. Create a div with a height of 100 to display the last message.

State Management

  1. Initialize two states to manage the last message and the input value.

  2. Incorporate these states within the UI, ensuring their proper rendering and functionality.

Refer the code below:

Backend Configuration

  1. Create a backend function named send-msg.

  2. 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".

Real-Time Messaging

  1. Import { useSocket } from '@magicjs.dev/frontend';

  2. Utilize the useSocket() hook to establish socket connection.

  3. Implement a useEffect() hook to subscribe to incoming messages and update the state accordingly.

  4. Ensure proper subscription management by unsubscribing within the hook.

Refer the snippet below.

Room Restriction

  1. Modify the backend to emit messages only to a specific room, e.g., "secret-room".

  2. Allow users to join and leave the room by invoking socket.joinRoom() and socket.leaveRoom() respectively in the frontend.

Refer the snippets below.

Expand for Tailwind styled code.

Testing

  1. Open two browsers with the same page.

  2. Test sending messages within the room, ensuring they are received in real-time only by members of the room.

Output in 2 browsers.

🎉 Congratulations! You have successfully implemented real-time messaging capabilities using MagicJS's socket feature.

Last updated