All files / src/hooks useNotifications.ts

100% Statements 19/19
100% Branches 0/0
100% Functions 9/9
100% Lines 19/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77                          2x 26x   15x               2x 13x                     2x 16x   16x     9x 9x               2x 11x   11x     4x 4x               2x 13x   13x     5x        
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
  getNotifications,
  getUnreadCount,
  markNotificationRead,
  markAllNotificationsRead,
  clearAllNotifications,
  Notification,
} from '../api/notifications';
 
/**
 * Hook to fetch all notifications
 */
export const useNotifications = (options?: { read?: boolean; limit?: number }) => {
  return useQuery<Notification[]>({
    queryKey: ['notifications', options],
    queryFn: () => getNotifications(options),
    staleTime: 30000, // 30 seconds
  });
};
 
/**
 * Hook to fetch unread notification count
 */
export const useUnreadNotificationCount = () => {
  return useQuery<number>({
    queryKey: ['notificationsUnreadCount'],
    queryFn: getUnreadCount,
    staleTime: 30000, // 30 seconds
    refetchInterval: 60000, // Refetch every minute
  });
};
 
/**
 * Hook to mark a notification as read
 */
export const useMarkNotificationRead = () => {
  const queryClient = useQueryClient();
 
  return useMutation({
    mutationFn: markNotificationRead,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['notifications'] });
      queryClient.invalidateQueries({ queryKey: ['notificationsUnreadCount'] });
    },
  });
};
 
/**
 * Hook to mark all notifications as read
 */
export const useMarkAllNotificationsRead = () => {
  const queryClient = useQueryClient();
 
  return useMutation({
    mutationFn: markAllNotificationsRead,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['notifications'] });
      queryClient.invalidateQueries({ queryKey: ['notificationsUnreadCount'] });
    },
  });
};
 
/**
 * Hook to clear all read notifications
 */
export const useClearAllNotifications = () => {
  const queryClient = useQueryClient();
 
  return useMutation({
    mutationFn: clearAllNotifications,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['notifications'] });
    },
  });
};