All files / src/viewmodels/tickets useTicketsViewModel.ts

18.18% Statements 6/33
100% Branches 0/0
0% Functions 0/1
18.18% Lines 6/33

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 481x 1x 1x   1x 1x                   1x                                                                
import { useCallback, useEffect, useState } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { listMyTickets } from '@/services/ticketService';
import type { TicketListItem } from '@/models/ticket';
import { ApiError } from '@/services/api';
import i18n from '@/i18n';
 
export interface TicketsViewModel {
  tickets: TicketListItem[];
  isLoading: boolean;
  error: string | null;
  refresh: () => Promise<void>;
  dismissError: () => void;
}
 
export function useTicketsViewModel(): TicketsViewModel {
  const { token } = useAuth();
  const [tickets, setTickets] = useState<TicketListItem[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
 
  const refresh = useCallback(async () => {
    if (!token) {
      setTickets([]);
      setIsLoading(false);
      return;
    }
    setIsLoading(true);
    setError(null);
    try {
      const response = await listMyTickets(token);
      setTickets(response.items ?? []);
    } catch (err) {
      setError(err instanceof ApiError ? err.message : i18n.t('errors.tickets_load_failed'));
    } finally {
      setIsLoading(false);
    }
  }, [token]);
 
  useEffect(() => {
    refresh();
  }, [refresh]);
 
  const dismissError = useCallback(() => setError(null), []);
 
  return { tickets, isLoading, error, refresh, dismissError };
}