MagicJS
mern.aiUniversityGitHub
  • Introduction to MagicJS
  • Why MagicJS?
  • Getting Started & Installation
  • Basic Guide
    • Create a new page using React
    • Navigate between pages
    • Create an API and integrate it with the frontend
    • Authenticate Users
      • Authorise based on Roles
    • Advanced State Management with useContent()
    • Perform CRUD Operations
    • Adding Realtime capabilities using socket
    • Handling file uploads and downloads
  • Advanced Guide
    • Understanding the concept of features in MagicJS
    • Using UI components & functions across multiple Magic Features
    • Advanced Routing of pages
    • Enable SSR
    • Access MongoDB
    • Styling pages using Tailwind CSS
  • Deploying
  • Update MagicJS
  • API References
    • Frontend
      • <LinkDisplay>
      • createSrc()
      • createUploader()
      • importUI()
      • loadConfig()
      • protected()
      • useParams()
      • useAxios()
      • useLogin()
      • useSocket()
      • useContent()
      • usePromise()
      • useNotification()
    • Backend
      • createBackendFunction()
      • data()
      • io()
      • ServerInstance()
      • utils
        • hash()
        • verifyHash()
        • initiateEmailVerification()
        • saveFileToUserUploads()
        • readFileFromUserUploads()
        • removeFileFromUserUploads()
        • assignRoleToUser()
        • unassignRoleFromUser()
        • findAllRolesByUser()
        • isUserInAnyRoles()
        • assignRoleToUser()
Powered by GitBook
On this page
  • Frontend
  • Backend

Was this helpful?

  1. API References
  2. Frontend

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.

  1. joinRoom()

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

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

const { subscribe, joinRoom } = useSocket();

React.useEffect(() => {
    const leave = joinRoom(`public/room`);
    return leave;
}, []);

React.useEffect(() => {
    const unsubscribe = subscribe(`refresh`, () => {
        // Function you want to call after emitting
        handleFetchLatestMessage();
    });
    return unsubscribe;
}, []);

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

import { createBackendFunction, data, io, useFunctionContext } from "@magicjs.dev/backend";
export default createBackendFunction(async function (message) {
    try {
        const messageCollection = data("messages"); // Fetching db
        const context = useFunctionContext(this);
        const userId = context.currentUser._id;
        const userName = context.currentUser.name;
        const messageItem = await messageCollection.insertOne({
            senderId: userId,
            senderName: userName,
            message
        });
        io().to(`public/room`).emit(`refresh`);
        return messageItem;
    } 
}});

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.

PrevioususeLogin() NextuseContent()

Last updated 1 year ago

Was this helpful?

Click here to refer GitHub.