# 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:

```tsx
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:

```tsx
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'.

[Click here to refer GitHub.](https://github.com/skyslit/magicjs.dev/blob/main/packages/frontend/src/use-notification.ts)
