All files / src/hooks useReloadCart.ts

100% Statements 31/31
100% Branches 6/6
100% Functions 5/5
100% Lines 28/28

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                52x 52x 52x 52x   52x 52x 52x     52x   52x 43x     43x 43x 43x   43x 43x 43x 43x   22x 14x   14x   14x       14x     43x 43x         52x 39x 39x     52x  
import { useState, useEffect, useCallback, useRef } from 'react';
import { useCartStore } from '../stores/useCartStore';
import { useLanguageStore } from '../stores/useLanguageStore';
import { useTranslation } from 'react-i18next';
import type { AxiosError } from 'axios';
import { useCustomSnackbar } from './useCustomSnackbar';
 
export function useReloadCart() {
  const loadCart = useCartStore(s => s.loadCart);
  const { notify } = useCustomSnackbar();
  const { t } = useTranslation('cart');
  const lang = useLanguageStore(s => s.lang);
 
  const [loading, setLoading] = useState(false);
  const [hasError, setHasError] = useState(false);
  const [isReloading, setIsReloading] = useState(false);
 
  // AbortController pour annuler les vieux appels
  const abortCtrlRef = useRef<AbortController | null>(null);
 
  const reload = useCallback(async () => {
    setIsReloading(true);
 
    // on annule l'appel précédent
    abortCtrlRef.current?.abort();
    const ctrl = new AbortController();
    abortCtrlRef.current = ctrl;
 
    setHasError(false);
    setLoading(true);
    try {
      await loadCart();
    } catch (err: unknown) {
      if ((err as AxiosError).code !== 'ERR_CANCELED') {
        setHasError(true);
 
        const code = (err as AxiosError).response?.status;
        const message =
          code === 404
            ? t('errors.error_not_found')
            : t('errors.error_load');
 
        notify(message, 'error');
      }
    } finally {
      setLoading(false);
      setIsReloading(false);
    }
  }, [loadCart, notify, t]);
 
  // auto-reload à chaque changement de langue
  useEffect(() => {
    reload();
    if (!loading) setIsReloading(false);
  }, [reload, lang]);
 
  return { loading, hasError, isReloading, reload };
}