Files
GNX-WEB/gnx-react/lib/hooks/usePolicy.ts
Iliyan Angelov 5ad9cbe3a6 update
2025-10-13 01:49:06 +03:00

129 lines
2.7 KiB
TypeScript

"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<void>;
}
interface UsePolicyReturn {
data: Policy | null;
isLoading: boolean;
error: Error | null;
refetch: () => Promise<void>;
}
/**
* Hook to fetch all policies
*/
export const usePolicies = (): UsePoliciesReturn => {
const [data, setData] = useState<PolicyListItem[] | null>(null);
const [loading, setLoading] = useState<boolean>(true);
const [error, setError] = useState<string | null>(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');
} 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<Policy | null>(null);
const [isLoading, setIsLoading] = useState<boolean>(true);
const [error, setError] = useState<Error | null>(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'));
} 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<Policy | null>(null);
const [isLoading, setIsLoading] = useState<boolean>(true);
const [error, setError] = useState<Error | null>(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'));
} finally {
setIsLoading(false);
}
};
useEffect(() => {
fetchData();
}, [id]);
return {
data,
isLoading,
error,
refetch: fetchData,
};
};