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:
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:
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'.
Last updated