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

useNotification()

The useNotification() function facilitates real-time notification handling in web applications, similar to a notification centre. It operates within the MagicJS framework, integrating backend and frontend components seamlessly.

Here's an example:

Frontend

To fetch and interact with the notification:

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

const { notifications, unreadCount, markAsRead } = useNotification();

return (
    <div>
        <p>{`Notification counter: ${unreadCount}`}</p>
        <div>
            {
                notifications.map((n) => (
                    <div key={n._id}>
                        <p>{n.payload.title}</p>
                        <button onClick={() => markAsRead([n._id])}>
                            Mark as read
                        </button>
                    </div>
                ))
            }
        </div>
        <button onClick={async () => {
            markAsRead(notifications.map((n) => n._id))
        }}>
            Mark all as read
        </button>
    </div>
)
  • It renders the notifications and a button to mark all notifications as read.

  • It fetches the unread notification count using the unreadCount variable.

  • For each notification, it renders a <div> with a unique key (n._id), a title (n.payload.title), and a "Mark as read" button if the notification has not been read yet (n.hasRead === false).

  • The "Mark as read" button calls the markAsRead function with the notification's ID when clicked.

  • There's a button labeled "Mark all as read", which marks all notifications as read by calling markAsRead with an array of all notification IDs.

  • Clicking on the 'Create Notification' button invokes the notifyServer and sends a notification.


Backend

To send a notification:

import { createBackendFunction, utils, useFunctionContext } from "@magicjs.dev/backend";

export default createBackendFunction(async function () {
    const ctx = useFunctionContext(this);

    await utils.sendNotification(
        [
            ctx.currentUser._id
        ],
        {
            title: 'Test at ' + (new Date()),
            message: 'Hello world'
        }
    );
})
  • It uses utils.sendNotification function to send a notification.

  • To send the notification to the current user, it accesses ctx.currentUser._id, add multiple recepients separated by a comma.

  • The second argument is an object containing the notification details, including the title and message. The title is dynamic, including the current date/time concatenated with the string 'Test at '. with a static message 'Hello world'.

PrevioususePromise()NextBackend

Last updated 1 year ago

Was this helpful?

Click here to refer GitHub.