"use client"; import { useState, useEffect } from 'react'; import { Policy, PolicyListItem, getPolicies, getPolicyByType, getPolicyById } from '../api/policyService'; interface UsePoliciesReturn { data: PolicyListItem[] | null; loading: boolean; error: string | null; refetch: () => Promise; } interface UsePolicyReturn { data: Policy | null; isLoading: boolean; error: Error | null; refetch: () => Promise; } /** * Hook to fetch all policies */ export const usePolicies = (): UsePoliciesReturn => { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const fetchData = async () => { try { setLoading(true); setError(null); const result = await getPolicies(); setData(result); } catch (err) { setError(err instanceof Error ? err.message : 'An error occurred'); console.error('Error fetching policies:', err); } finally { setLoading(false); } }; useEffect(() => { fetchData(); }, []); return { data, loading, error, refetch: fetchData, }; }; /** * Hook to fetch a policy by type */ export const usePolicy = (type: 'privacy' | 'terms' | 'support' | null): UsePolicyReturn => { const [data, setData] = useState(null); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(null); const fetchData = async () => { if (!type) { setIsLoading(false); return; } try { setIsLoading(true); setError(null); const result = await getPolicyByType(type); setData(result); } catch (err) { setError(err instanceof Error ? err : new Error('An error occurred')); console.error('Error fetching policy:', err); } finally { setIsLoading(false); } }; useEffect(() => { fetchData(); }, [type]); return { data, isLoading, error, refetch: fetchData, }; }; /** * Hook to fetch a policy by ID */ export const usePolicyById = (id: number | null): UsePolicyReturn => { const [data, setData] = useState(null); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(null); const fetchData = async () => { if (!id) { setIsLoading(false); return; } try { setIsLoading(true); setError(null); const result = await getPolicyById(id); setData(result); } catch (err) { setError(err instanceof Error ? err : new Error('An error occurred')); console.error('Error fetching policy:', err); } finally { setIsLoading(false); } }; useEffect(() => { fetchData(); }, [id]); return { data, isLoading, error, refetch: fetchData, }; };