useCounts

Learn how to use the useCounts hook to fetch notification counts in your React application

The useCounts hook provides a way to fetch various notification counts, including unread, unseen, and total counts. This hook is useful for displaying notification badges and indicators in your application.

Hook Parameters

ParameterTypeRequiredDescription
storeIdstringNoFilter counts by a specific store ID
queryobjectNoAdditional query parameters for filtering

Return Value

type CountsReturn = {
  data: {
    unreadCount: number;
    unseenCount: number;
    total: number;
  };
  isLoading: boolean;
  error: Error | null;
  refetch: () => void;
};

Example Usage

Here's how to use the useCounts hook to fetch and display notification counts:

import { useCounts } from '@novu/react';
 
function NotificationBadge() {
  const { data, isLoading, error } = useCounts();
 
  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;
 
  return (
    <div>
      <span>Unread: {data?.unreadCount}</span>
      <span>Unseen: {data?.unseenCount}</span>
      <span>Total: {data?.total}</span>
    </div>
  );
}

With Store ID

You can filter counts for a specific store:

function StoreNotifications({ storeId }) {
  const { data, isLoading } = useCounts({
    storeId: storeId,
  });
 
  if (isLoading) return <div>Loading...</div>;
 
  return (
    <div>
      <span>Store Notifications: {data?.total}</span>
      <span>Unread: {data?.unreadCount}</span>
    </div>
  );
}

With Query Filters

You can also apply additional filters using the query parameter:

function FilteredNotifications() {
  const { data, isLoading } = useCounts({
    query: {
      templates: ['welcome-template', 'order-update'],
      emails: ['user@example.com'],
    },
  });
 
  if (isLoading) return <div>Loading...</div>;
 
  return (
    <div>
      <span>Filtered Notifications: {data?.total}</span>
      <span>Unread: {data?.unreadCount}</span>
    </div>
  );
}

The counts are automatically updated in real-time when notifications are marked as read/unread or when new notifications arrive.

On this page