All files / src/common/hooks useUnreadCount.ts

88.35% Statements 167/189
81.63% Branches 40/49
80% Functions 4/5
88.35% Lines 167/189

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 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 2551x 1x 1x 1x 1x     1x 1x 1x 1x                       1x 58x 58x 58x 58x 58x 58x 58x     58x 26x 6x 6x 20x 58x     58x 58x 25x   25x 9x 9x   16x 25x 58x 58x     58x 58x 58x 58x 58x 58x 58x 58x 21x             21x 21x 21x 21x   21x   21x 21x 21x 21x   21x 21x   21x   21x 21x 21x 21x 21x 21x 21x 21x 21x   21x 21x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 21x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x     58x 51x 26x 26x 26x 58x       58x 48x 28x 28x 58x     58x   8x 4x 4x     8x 4x 4x 4x     4x 4x 4x 4x 4x 8x 58x     58x 58x   46x               46x 46x 46x   46x 46x 46x 46x     46x 5x 5x 46x 58x       58x 3x 55x 55x         58x 58x 58x 58x 58x 58x 58x 58x           1x 3x 3x 3x 3x   3x 3x   2x     2x 3x                     2x 2x 2x   2x 2x 2x 2x 2x 2x 2x   1x 2x 2x 2x 3x   3x 3x  
import { AuthContext } from '@common/contexts/AuthContext';
import { optimizedNewsletterService } from '@common/services/optimizedNewsletterService';
import { useLogger } from '@common/utils/logger/useLogger';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useCallback, useContext, useEffect, useMemo, useRef } from 'react';
 
// Cache time constants (in milliseconds)
const STALE_TIME = 5 * 60 * 1000; // 5 minutes stale time
const CACHE_TIME = 60 * 60 * 1000; // 1 hour cache time
const REFETCH_INTERVAL = 5 * 60 * 1000; // 5 minutes refetch interval
const DEBOUNCE_DELAY = 500; // 500ms debounce for invalidations
 
interface UnreadCountData {
  total: number;
  bySource: Record<string, number>;
}
 
/**
 * Optimized hook for fetching unread newsletter counts
 * Fetches all counts in a single query and uses React Query's select for per-source counts
 * Implements debouncing to reduce database queries
 */
export const useUnreadCount = (sourceId?: string | null) => {
  const log = useLogger('useUnreadCount');
  const auth = useContext(AuthContext);
  const user = auth?.user;
  const queryClient = useQueryClient();
  const initialLoadComplete = useRef(false);
  const previousCount = useRef<number | null>(null);
  const debounceTimeoutRef = useRef<NodeJS.Timeout | null>(null);
 
  // Single query key for all unread count data
  const queryKey = useMemo(() => {
    if (!user?.id) {
      return ['unreadCount', 'all', null];
    }
    return ['unreadCount', 'all', user.id];
  }, [user?.id]);
 
  // Selector function to extract the needed count
  const selectCount = useCallback(
    (data: UnreadCountData | undefined): number => {
      if (!data) return 0;
 
      if (sourceId) {
        return data.bySource[sourceId] || 0;
      }
 
      return data.total;
    },
    [sourceId]
  );
 
  // Single query that fetches all unread counts
  const {
    data: unreadCount = 0,
    isLoading,
    isError,
    error,
  } = useQuery<UnreadCountData, Error, number>({
    queryKey,
    queryFn: async () => {
      if (!user) {
        log.debug('No user, returning empty unread count data', {
          action: 'fetch_unread_count_no_user',
        });
        return { total: 0, bySource: {} };
      }
 
      log.debug('Fetching all unread counts', {
        action: 'fetch_unread_count_start',
        metadata: { userId: user.id },
      });
 
      try {
        // Fetch both total and per-source counts in parallel
        const [totalResult, bySourceResult] = await Promise.all([
          optimizedNewsletterService.getUnreadCount(),
          optimizedNewsletterService.getUnreadCountBySource(),
        ]);
 
        const total = totalResult || 0;
        const bySource = bySourceResult || {};
 
        const result = { total, bySource };
 
        log.debug('Unread count result', {
          action: 'fetch_unread_count_result',
          metadata: {
            total,
            sourceCount: Object.keys(bySource).length,
            sourceId,
            count: sourceId ? bySource[sourceId] || 0 : total,
          },
        });
 
        return result;
      } catch (error) {
        log.error(
          'Error fetching unread counts',
          {
            action: 'fetch_unread_count_error',
            metadata: { userId: user.id },
          },
          error instanceof Error ? error : new Error(String(error))
        );
        throw error;
      }
    },
    select: selectCount,
    enabled: !!user,
    staleTime: STALE_TIME,
    gcTime: CACHE_TIME,
    refetchOnWindowFocus: false,
    refetchOnMount: false,
    refetchOnReconnect: true,
    refetchInterval: REFETCH_INTERVAL,
    refetchIntervalInBackground: false,
    networkMode: 'always',
  });
 
  // Track initial load
  useEffect(() => {
    if (!isLoading && !initialLoadComplete.current) {
      initialLoadComplete.current = true;
      previousCount.current = unreadCount;
    }
  }, [isLoading, unreadCount]);
 
  // Only update the previous count when we have a stable value
  // This prevents the count from changing during rapid updates
  useEffect(() => {
    if (initialLoadComplete.current && unreadCount !== undefined) {
      previousCount.current = unreadCount;
    }
  }, [unreadCount]);
 
  // Debounced invalidation function
  const debouncedInvalidate = useCallback(() => {
    // Clear any existing timeout
    if (debounceTimeoutRef.current) {
      clearTimeout(debounceTimeoutRef.current);
    }
 
    // Set new timeout
    debounceTimeoutRef.current = setTimeout(() => {
      log.debug('Invalidating unread count after debounce', {
        action: 'invalidate_unread_count_debounced',
      });
 
      // Single invalidation for all unread count data
      queryClient.invalidateQueries({
        queryKey,
        exact: true,
        refetchType: 'active', // Only refetch active queries
      });
    }, DEBOUNCE_DELAY);
  }, [queryClient, log, queryKey]);
 
  // Listen for newsletter updates and invalidate unread count with debouncing
  useEffect(() => {
    if (!user) return;
 
    const handleNewsletterUpdate = () => {
      log.debug('Newsletter update event received', {
        action: 'newsletter_update_event',
      });
      debouncedInvalidate();
    };
 
    // Listen for custom events from newsletter actions
    window.addEventListener('newsletter:read-status-changed', handleNewsletterUpdate);
    window.addEventListener('newsletter:archived', handleNewsletterUpdate);
    window.addEventListener('newsletter:deleted', handleNewsletterUpdate);
 
    return () => {
      window.removeEventListener('newsletter:read-status-changed', handleNewsletterUpdate);
      window.removeEventListener('newsletter:archived', handleNewsletterUpdate);
      window.removeEventListener('newsletter:deleted', handleNewsletterUpdate);
 
      // Clear debounce timeout on cleanup
      if (debounceTimeoutRef.current) {
        clearTimeout(debounceTimeoutRef.current);
      }
    };
  }, [user, debouncedInvalidate, log]);
 
  // Return 0 during initial load or when there's an error, then return actual count or fallback to previous count
  // When there's an error, we should return 0 regardless of what the selector returns
  const displayCount = isError
    ? 0
    : unreadCount !== undefined
      ? unreadCount
      : previousCount.current !== null
        ? previousCount.current
        : 0;
 
  return {
    unreadCount: displayCount,
    isLoading: !initialLoadComplete.current && isLoading,
    isError,
    error,
    invalidateUnreadCount: debouncedInvalidate,
  };
};
 
/**
 * Hook to prefetch all unread counts
 * Useful for warming the cache before navigation
 */
export const usePrefetchUnreadCounts = () => {
  const auth = useContext(AuthContext);
  const user = auth?.user;
  const queryClient = useQueryClient();
  const log = useLogger('usePrefetchUnreadCounts');
 
  const prefetchCounts = useCallback(async () => {
    if (!user) return;
 
    const queryKey = ['unreadCount', 'all', user.id];
 
    // Check if data is already fresh
    const state = queryClient.getQueryState(queryKey);
    if (state?.dataUpdatedAt && Date.now() - state.dataUpdatedAt < STALE_TIME) {
      log.debug('Unread counts are fresh, skipping prefetch', {
        action: 'prefetch_skip',
        metadata: {
          dataAge: Date.now() - state.dataUpdatedAt,
          staleTime: STALE_TIME,
        },
      });
      return; // Data is fresh, no need to prefetch
    }
 
    log.debug('Prefetching unread counts', {
      action: 'prefetch_start',
    });
 
    await queryClient.prefetchQuery({
      queryKey,
      queryFn: async () => {
        const [total, bySource] = await Promise.all([
          optimizedNewsletterService.getUnreadCount(),
          optimizedNewsletterService.getUnreadCountBySource(),
        ]);
 
        return { total, bySource };
      },
      staleTime: STALE_TIME,
    });
  }, [user, queryClient, log]);
 
  return { prefetchUnreadCounts: prefetchCounts };
};