commit16
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import type { InvestmentMapArea } from './interactive-investment-map';
|
||||
|
||||
export type TerritoryGeometryContext = {
|
||||
selected_geometry_available: boolean;
|
||||
context_geometry_count: number;
|
||||
areas: InvestmentMapArea[];
|
||||
truncated: boolean;
|
||||
};
|
||||
|
||||
export function useTerritoryGeometry(
|
||||
territoryId?: string,
|
||||
endpoint = '/api/v1/investment/territory-geometries',
|
||||
) {
|
||||
const key = JSON.stringify([territoryId, endpoint]);
|
||||
const [result, setResult] = useState<{
|
||||
key: string;
|
||||
context: TerritoryGeometryContext | null;
|
||||
error: string;
|
||||
}>({ key, context: null, error: '' });
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setResult({ key, context: null, error: '' });
|
||||
if (!territoryId) return () => controller.abort();
|
||||
void fetch(
|
||||
`${endpoint}?${new URLSearchParams({ territory_id: territoryId })}`,
|
||||
{
|
||||
signal: controller.signal,
|
||||
headers: { Accept: 'application/json' },
|
||||
},
|
||||
)
|
||||
.then(async (response) => {
|
||||
if (!response.ok)
|
||||
throw new Error(
|
||||
'Não foi possível consultar os limites administrativos.',
|
||||
);
|
||||
return response.json() as Promise<TerritoryGeometryContext>;
|
||||
})
|
||||
.then((context) => {
|
||||
if (!controller.signal.aborted)
|
||||
setResult({ key, context, error: '' });
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (!controller.signal.aborted)
|
||||
setResult({
|
||||
key,
|
||||
context: null,
|
||||
error:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Erro de ligação.',
|
||||
});
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [key, territoryId, endpoint]);
|
||||
return result.key === key ? result : { key, context: null, error: '' };
|
||||
}
|
||||
Reference in New Issue
Block a user