All files / src/hooks useStockChangeNotifier.ts

100% Statements 16/16
100% Branches 6/6
100% Functions 4/4
100% Lines 15/15

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            10x 10x 10x   10x 10x 5x 5x     5x 5x 6x   6x 2x       4x 2x                 5x      
import { useEffect, useRef } from 'react';
import { useCustomSnackbar } from '../hooks/useCustomSnackbar';
import { useTranslation } from 'react-i18next';
import type { CartItem } from '../stores/useCartStore';
 
export function useStockChangeNotifier(items: CartItem[], isReloading: boolean) {
  const prevRef = useRef<CartItem[]>([]);
  const { notify } = useCustomSnackbar();
  const { t } = useTranslation('cart');
 
  useEffect(() => {
    if (!isReloading) {
      prevRef.current = items;
      return;
    }
 
    const prev = prevRef.current;
    prev.forEach(oldItem => {
      const cur = items.find(i => i.id === oldItem.id);
 
      if (!cur) {
        notify(
          t('cart.removed_unavailable', { name: oldItem.name }),
          'warning'
        );
      } else if (cur.quantity < oldItem.quantity) {
        notify(
          t('cart.quantity_reduced', {
            name: cur.name,
            count: cur.quantity
          }),
          'warning'
        );
      }
    });
    prevRef.current = items;
  }, [items, isReloading, notify, t]);
}