mirror of
https://github.com/SamyRai/turash.git
synced 2025-12-26 23:01:33 +00:00
52 lines
2.4 KiB
TypeScript
52 lines
2.4 KiB
TypeScript
import { useQuery } from '@tanstack/react-query';
|
|
import { useMemo } from 'react';
|
|
import { historicalData } from '@/data/historicalData';
|
|
import { getSimilarOrganizations } from '@/services/organizations-api';
|
|
import { useOrganization as useOrganizationAPI } from '@/hooks/api';
|
|
import { useOrganizations } from '@/hooks/useOrganizations';
|
|
|
|
export const useOrganizationData = (organizationId: string | undefined) => {
|
|
const { data: organization, isLoading, error } = useOrganizationAPI(organizationId);
|
|
const { organizations } = useOrganizations();
|
|
|
|
const relatedLandmark = useMemo(() => {
|
|
if (!organization) return null;
|
|
return historicalData.find((landmark) => landmark.relatedOrgId === organization.ID) || null;
|
|
}, [organization]);
|
|
|
|
// Use backend API for similar organizations
|
|
// Returns empty structure immediately to prevent blocking render
|
|
const { data: similarOrgsData, isLoading: isLoadingSimilar } = useQuery({
|
|
queryKey: ['similarOrganizations', organizationId],
|
|
queryFn: () => getSimilarOrganizations(organizationId!, 5),
|
|
enabled: !!organizationId,
|
|
placeholderData: { organizations: [] }, // Render immediately with empty array
|
|
});
|
|
|
|
// Map backend response to Organization objects - backend returns full Organization objects
|
|
const similarOrgs = useMemo(() => {
|
|
if (!similarOrgsData?.organizations || !Array.isArray(similarOrgsData.organizations)) return [];
|
|
if (!organizations || !Array.isArray(organizations)) return [];
|
|
|
|
// Backend returns full Organization objects with ID field (capital)
|
|
// Try to find matching orgs in the organizations context for consistency,
|
|
// otherwise use the similar orgs directly from the API
|
|
return similarOrgsData.organizations
|
|
.map((similar) => {
|
|
if (!similar?.ID) return null;
|
|
// Prefer the organization from context if available (may have additional data)
|
|
const foundOrg = organizations.find((org) => org?.ID === similar.ID);
|
|
return foundOrg || similar;
|
|
})
|
|
.filter((org): org is NonNullable<typeof org> => org !== undefined && org !== null);
|
|
}, [similarOrgsData, organizations]);
|
|
|
|
return {
|
|
organization: organization || undefined,
|
|
relatedLandmark: relatedLandmark || null,
|
|
similarOrgs: Array.isArray(similarOrgs) ? similarOrgs : [],
|
|
isLoading: isLoading || isLoadingSimilar,
|
|
error: error instanceof Error ? error : error ? new Error(String(error)) : null,
|
|
};
|
|
};
|