All files / src/hooks useCIAContentService.ts

100% Statements 37/37
100% Branches 6/6
100% Functions 3/3
100% Lines 37/37

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 561x 1x       1x           1x 335x 335x 335x 335x   335x 243x 243x   243x   243x 242x 242x 243x 1x 1x 243x 243x 243x 243x     335x   1x 1x 1x   335x 242x 335x   335x 335x 335x 335x 335x 335x 335x     1x  
import { useEffect, useState } from "react";
import {
  CIAContentService,
  createCIAContentService,
} from "../services/ciaContentService";
import { toErrorObject } from "../utils";
 
/**
 * Hook to access the CIA content service with loading and error states
 * @returns Object containing the CIA content service, loading state, and error state
 */
export const useCIAContentService = () => {
  const [ciaContentService, setCIAContentService] =
    useState<CIAContentService | null>(null);
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const [error, setError] = useState<Error | null>(null);
 
  const initService = async () => {
    try {
      setIsLoading(true);
      // Create the service using the createCIAContentService factory function
      const service = createCIAContentService();
      // Wait for any async initialization to complete
      await service.initialize();
      setCIAContentService(service);
      setError(null);
    } catch (err) {
      setCIAContentService(null);
      setError(toErrorObject(err));
    } finally {
      setIsLoading(false);
    }
  };
 
  // Refresh function to retry initialization if needed
  const refresh = () => {
    // Make sure we set isLoading immediately, not after the async part
    setIsLoading(true);
    initService();
  };
 
  useEffect(() => {
    initService();
  }, []);
 
  return {
    ciaContentService,
    isLoading,
    error,
    refresh,
  };
};
 
// Keep the default export for backward compatibility
export default useCIAContentService;