MagicBell React Headless SDK

This package contains React headless components and hooks to build a notification inbox for your site powered by MagicBell. It's the package that drives the MagicBell React SDK.

MagicBellProvider

The MagicBellProvider component is the main component for building a custom notification inbox. It fetches configuration from MagicBell and keeps the list of notifications updated in real time.

This is a headless component, so you can safely wrap your entire app in this component.

jsx
import React from 'react';
import ReactDOM from 'react-dom';
import { MagicBellProvider } from '@magicbell/react-headless';

ReactDOM.render(
  
    
  ,
  document.body,
);

These are all the properties accepted by this component.

PropertyTypeDescription
apiKeystringThe API key of your magicbell.io project
userEmailstringThe email of the user you want to show notifications for
userExternalIdstringThe external ID of the user you want to show notifications for
userKeystringThe HMAC for the user. It is recommended to enable HMAC authentication but not required
childrenReact.ReactChildrenThe children to be wrapped in aMagicBellContext.Provider
storesobject[]An optional object containing the definitions of the notification stores to create.

Splitting the inbox

By default, one store for notifications is automatically configured. However, you can split your notification inbox if you want to.

For example, to split your inbox in read and unread notifications define each store as shown below:

jsx
import React from 'react';
import ReactDOM from 'react-dom';
import { MagicBellProvider } from '@magicbell/react-headless';

ReactDOM.render(
  
    
  ,
  document.body,
);

Each store needs an id and the query params (defaultQueryParams) used for filtering notifications when you fetch them from the MagicBell API server.

useNotifications

Hook to get a store of notifications for the current authenticated user. Returns a notification store.

Use this hook in the component that will render a list of notifications.

javascript
import { useNotifications } from '@magicbell/react-headless';

function Notifications() {
  const store = useNotifications();

  return (
    
    {store.notifications.map((notification) => (
  • {notification.title}
  • ))}
); }

When you split your inbox, provide the id of your store, e.g.:

javascript
import { useNotifications } from '@magicbell/react-headless';

function Notifications() {
  const store = useNotifications('unread');

  return (
    
    {store.notifications.map((notification) => (
  • {notification.title}
  • ))}
); }

Keep in mind, that the unread store should have been defined previously (see splitting the inbox).

useBell

This hook is very similar to the useNotifications hook. It will return a notification store.

javascript
import { useBell } from '@magicbell/react-headless';

function NotificationsList() {
  const { unreadCount, markAllAsSeen } = useBell();

  return (
    
  );
}

The unreadCount will be updated in realtime when new notifications arrive.

The only difference between the useNotifications hook and this one is the implementation of the markAllAsSeen function. This function will mark notifications as seen in other tabs, but not the current. This can help users to identify new notifications (based on a style you would implement, for example).

When you split the notification inbox, you will have to provide the id of the store you want to fetch notifications from:

javascript
import { useBell } from '@magicbell/react-headless';

function NotificationsList() {
  const { unreadCount, markAllAsSeen } = useBell({ storeId: 'unread' });

  return (
    
  );
}

useMagicBellEvent

This is a hook to listen to events, including realtime ones (generated in other tabs). Use it to be notified when a realtime event happens, for example to play a sound when a new notification arrives (read more in our guides).

javascript
import { useMagicBellEvent } from '@magicbell/react-headless';

useMagicBellEvent('notifications.new', (notification) => {
  // Do something like showing a push notification
});

This is a list of events you can listen to:

Event nameDescription
*Any event
notifications.newA new notification for the authenticated user was created
notifications.readA notification was marked as read
notifications.read.allAll notifications were marked as read
notifications.unreadA notification was marked as unread
notifications.seen.allAll notifications were marked as seen
notifications.deleteA notification was deleted
disconnectedThe websocket connection was dropped
reconnectedThe websocket connection was reestablished

You can also limit the source of the events you want to listen to:

  • remote, to listen to events generated in other tabs or the MagicBell server only
  • local, to listen to events generated in the same tab only
  • any, to listen to all events regardless of where it was generated

It is set to any by default.

javascript
import { useMagicBellEvent } from '@magicbell/react-headless';

useMagicBellEvent('notifications.new', callbackFn, { source: 'remote' });

useNotification

Use this hook in the component that renders a notification. It will return a Notification object with all the methods needed to mutate it.

javascript
import { useNotification } from '@magicbell/react-headless';

function Notification(rawNotification) {
  const notification = useNotification();

  const handleClick = () => {
    if (notification.isRead) notification.markAsUnread();
    else notification.markAsRead();
  };

  return (
    
  );
}

useNotificationPreferences

Use this hook to fetch and update the notification preferences for the user.

javascript
import { useNotificationPreferences } from '@magicbell/react-headless';

function NotificationPreferences() {
  const { fetch, categories } = useNotificationPreferences();

  useEffect(() => {
    fetch();
  }, []);

  return (
    
    {categories.map((category) => (
  • {category.label}

    {category.channels.map((channel) => (

    {channel.label}: {channel.enabled}

    ))}
  • ))}
); }

The notification store

Some of the hooks described above return a notification store which implement this interface:

typescript
interface INotificationStore {
  unseenCount: number;
  unreadCount: number;
  total: number;
  perPage: number;
  totalPages: number;
  currentPage: number;
  notifications: Notification[];

  isEmpty: boolean;
  hasNextPage: boolean;

  fetch: (queryParams) => Promise;
  fetchNextPage: (queryParams) => Promise;
  markAllAsRead: () => Promise;
  markAllAsSeen: () => Promise;
}

fetch

Fetch notifications from the magicbell server. The pagination data is also updated. The provided query parameters are included in the request to the server.

The response is appended to the current array of notifications, so it can be used as the view model for an infinite scroll list. If you want to reset the collection instead, pass the reset: true option to this method:

js
notifications.fetch({ page: 2 }, { reset: true });

fetchNextPage

This method is simply wrapping the fetch method, sending as a parameter the next page of notifications. You can include query parameters to this method.

markAllAsRead

Makes a POST request to the read notifications API endpoint. It also sets the unreadCount of the store to 0 and the readAt attribute of all notifications to the current time.

markAllAsSeen

Makes a POST request to the seen notifications API endpoint. It also sets the unseenCount of the store to 0 and the seenAt attribute of all notifications to the current time.