All files / src/hooks useCategories.ts

100% Statements 48/48
88.88% Branches 8/9
100% Functions 3/3
100% Lines 48/48

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 491x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 14x 14x 14x 14x 14x 14x 14x 1x 22x 22x 22x 22x 22x 22x 11x 11x 11x 11x 11x 11x 8x 11x 3x 3x 11x 11x 11x 11x 11x 11x 22x 22x 22x 22x  
"use client";
 
import { useState, useEffect } from "react";
import { getCategories, Category as ApiCategory } from "@/lib/api/categories";
 
// Extended category type for UI use with additional computed properties
export interface Category extends ApiCategory {
  name: string; // Alias for title
  products: number; // Alias for productCount
  isRefined: boolean;
  children?: Category[];
}
 
// Transform API category to UI category
function transformCategory(apiCategory: ApiCategory): Category {
  return {
    ...apiCategory,
    name: apiCategory.title,
    products: apiCategory.productCount ?? 0,
    isRefined: false};
}
 
export function useCategories(includeProductCount = false) {
  const [categories, setCategories] = useState<Category[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
 
  useEffect(() => {
    const fetchCategories = async () => {
      setLoading(true);
      setError(null);
 
      try {
        const data = await getCategories(includeProductCount);
        setCategories(data.map(transformCategory));
      } catch (err) {
        const error = err instanceof Error ? err : new Error("Failed to load categories");
        setError(error.message);
      } finally {
        setLoading(false);
      }
    };
 
    fetchCategories();
  }, [includeProductCount]);
 
  return { categories, loading, error };
}