• Custom React hook to manage notifications within an application.

    Parameters

    • Optional options: useNotificationsParams = {}

      Optional configuration for the hook.

    Returns UseNotificationsReturn

    An object containing notification data and utility methods. The returning object contains:

    • fetched: Boolean indicating whether notifications have been successfully fetched from the server.
    • notifications: The list of notifications currently fetched and not marked as deleted.
    • toNotify: The list of new notifications fetched during polling (if polling is enabled).
    • currentPage: The current page index for paginated notifications.
    • markAllAsRead: NotificationMarkAllAsReadMethod - Function to mark all notifications as read.
    • refetch: NotificationFetchMethod - Function to refetch the notifications from the server.
    • fetchMore: NotificationFetchMoreMethod - Function to fetch additional notifications based on pagination parameters.

    Implementation Details

    • Polling: Uses useInterval to poll new notifications, controlled by NOTIFICATIONS_POLL_PERIOD from usePlayMakersConfig.
    • Pagination: Managed with usePagination, supporting fetching more pages or refreshing the last page.
    • React Lifecycle: Initial fetch and cleanup are handled with useEffect based on userData state changes.
    • Error Handling: Logs errors during API interactions and rethrows them with additional context.

    Example

    // Using the hook in a component
    import { useNotifications } from 'react-playmakers';

    const NotificationComponent = () => {
    const {
    notifications,
    toNotify,
    currentPage,
    fetchMore,
    refetch,
    markAllAsRead,
    } = useNotifications({ poll: true, params: { page: 1, limit: 10 } });

    // Handle new notifications when they arrive
    useEffect(() => {
    if (toNotify.length > 0) {
    alert("You have new notifications!");
    }
    }, [toNotify]);

    // Load more notifications when the user scrolls or clicks "Load More"
    const loadMoreNotifications = () => {
    fetchMore();
    };

    // Mark all notifications as read when the user clicks a button
    const markAllAsReadHandler = () => {
    markAllAsRead();
    };

    // Refresh the list of notifications manually
    const refreshNotifications = () => {
    refetch();
    };

    return (
    <div>
    <h2>Notifications</h2>
    <ul>
    {notifications.map((notification) => (
    <li key={notification.id}>
    {notification.message} {notification.seen ? "(Read)" : "(Unread)"}
    </li>
    ))}
    </ul>
    <button onClick={loadMoreNotifications}>Load More</button>
    <button onClick={markAllAsReadHandler}>Mark All as Read</button>
    <button onClick={refreshNotifications}>Refresh Notifications</button>
    </div>
    );
    };

Generated using TypeDoc