|
| 1 | +"use client" |
| 2 | + |
| 3 | +import { useEffect, useRef, useState } from "react" |
| 4 | +import { apiFetch } from "@/utils/apiFetch" |
| 5 | +import API_ROUTES, { apiBaseUrl } from "@/utils/apiRoutes" |
| 6 | +import { SearchResponse } from "@/utils/api" |
| 7 | +import { useAuth } from "@/providers/AuthProvider" |
| 8 | + |
| 9 | +export function useUnitOfficers(unitUid: string | undefined, enabled: boolean) { |
| 10 | + const { accessToken } = useAuth() |
| 11 | + const [officers, setOfficers] = useState<SearchResponse[]>([]) |
| 12 | + const [loading, setLoading] = useState<boolean>(false) |
| 13 | + const [error, setError] = useState<Error | null>(null) |
| 14 | + const fetchedRef = useRef(false) |
| 15 | + |
| 16 | + useEffect(() => { |
| 17 | + if (!enabled || fetchedRef.current || !unitUid || !accessToken) return |
| 18 | + |
| 19 | + fetchedRef.current = true |
| 20 | + setLoading(true) |
| 21 | + setError(null) |
| 22 | + |
| 23 | + // /api/v1/agencies/52192a89b0144fe6bf624239ed16d5db/officers?page=268&include=employment&per_page=1 |
| 24 | + apiFetch( |
| 25 | + `${apiBaseUrl}${API_ROUTES.agencies.profile(unitUid)}/officers?page=1&per_page=25&include=employment`, |
| 26 | + { |
| 27 | + headers: { |
| 28 | + Authorization: `Bearer ${accessToken}` |
| 29 | + } |
| 30 | + } |
| 31 | + ) |
| 32 | + .then((res) => res.json()) |
| 33 | + .then((data) => { |
| 34 | + setOfficers(data.results ?? []) |
| 35 | + }) |
| 36 | + .catch((err) => setError(err instanceof Error ? err : new Error(String(err)))) |
| 37 | + .finally(() => setLoading(false)) |
| 38 | + }, [accessToken, enabled, unitUid]) |
| 39 | + |
| 40 | + return { officers, loading, error } |
| 41 | +} |
0 commit comments