All files / src/common/components CacheInitializer.tsx

72.72% Statements 24/33
80% Branches 4/5
50% Functions 1/2
72.72% Lines 24/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 48 49 501x 1x 1x           1x 26x 26x 26x     26x   26x 26x 25x 26x   1x 1x 1x 1x 1x 1x 1x 26x     26x       26x 26x     1x                    
import { useMemo, useState, useEffect } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { createCacheManager, getCacheManagerSafe } from "../utils/cacheUtils";
 
type CacheInitializerProps = {
  children?: React.ReactNode;
};
 
export const CacheInitializer: React.FC<CacheInitializerProps> = ({
  children,
}) => {
  const queryClient = useQueryClient();
 
  // Initialize cache manager synchronously
  const isInitialized = useMemo(() => {
    // Try to get the cache manager first to avoid re-initialization
    const existingManager = getCacheManagerSafe();
    if (existingManager) {
      return true;
    } else {
      // If not initialized, create a new cache manager
      createCacheManager(queryClient, {
        enableOptimisticUpdates: true,
        enableCrossFeatureSync: true,
        enablePerformanceLogging: process.env.NODE_ENV === "development",
      });
      return true;
    }
  }, [queryClient]);
 
  // Only render children once the cache manager is initialized
  if (!isInitialized) {
    return null; // Or a loading spinner
  }
 
  return <>{children}</>;
};
 
// Export a hook to check if cache is initialized
export const useIsCacheInitialized = (): boolean => {
  const [isInitialized, setIsInitialized] = useState(false);
 
  useEffect(() => {
    const manager = getCacheManagerSafe();
    setIsInitialized(!!manager);
  }, []);
 
  return isInitialized;
};