2021-02-22 01:59:24 -05:00
|
|
|
import { useCallback, useEffect, useState } from 'react';
|
|
|
|
|
2021-02-24 02:48:09 -05:00
|
|
|
import { Building, BuildingAttributeVerificationCounts } from '../models/building';
|
2021-02-22 01:59:24 -05:00
|
|
|
import { apiGet } from '../apiHelpers';
|
|
|
|
|
2021-08-22 21:26:58 -04:00
|
|
|
/**
|
|
|
|
*
|
|
|
|
* @param buildingId Requested building ID
|
|
|
|
* @param preloadedData Data preloaded through SSR, to return before the request is first sent
|
|
|
|
* @param includeUserAttributes Should the building-user attributes be included in the result? This requires login session cookies to be present
|
|
|
|
* @returns
|
|
|
|
*/
|
|
|
|
export function useBuildingData(buildingId: number, preloadedData: Building, includeUserAttributes: boolean = false): [Building, (updatedBuilding: Building) => void, () => void] {
|
2021-02-22 01:59:24 -05:00
|
|
|
const [buildingData, setBuildingData] = useState<Building>(preloadedData);
|
|
|
|
const [isOld, setIsOld] = useState<boolean>(preloadedData == undefined);
|
|
|
|
|
|
|
|
const fetchData = useCallback(async () => {
|
|
|
|
if(buildingId == undefined) {
|
|
|
|
setBuildingData(undefined);
|
|
|
|
setIsOld(false);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
try {
|
2021-08-22 21:26:58 -04:00
|
|
|
let [building, buildingUprns] = await Promise.all([
|
|
|
|
apiGet(`/api/buildings/${buildingId}.json${includeUserAttributes ? '?user_attributes=true' : ''}`),
|
2021-02-22 01:59:24 -05:00
|
|
|
apiGet(`/api/buildings/${buildingId}/uprns.json`)
|
|
|
|
]);
|
|
|
|
|
|
|
|
building.uprns = buildingUprns.uprns;
|
2021-08-22 21:26:58 -04:00
|
|
|
building = Object.assign(building, {...building.user_attributes});
|
|
|
|
delete building.user_attributes;
|
2021-02-22 01:59:24 -05:00
|
|
|
|
|
|
|
setBuildingData(building);
|
|
|
|
} catch(error) {
|
|
|
|
console.error(error);
|
|
|
|
// TODO: add UI for API errors
|
|
|
|
}
|
|
|
|
setIsOld(false);
|
|
|
|
}, [buildingId]);
|
|
|
|
|
2021-02-24 02:48:09 -05:00
|
|
|
const updateData = useCallback((building: Building) => {
|
2021-02-24 03:41:48 -05:00
|
|
|
if(building == undefined) {
|
|
|
|
setBuildingData(building);
|
|
|
|
} else {
|
|
|
|
if(building.verified == undefined) {
|
|
|
|
building.verified = {} as BuildingAttributeVerificationCounts;
|
|
|
|
}
|
|
|
|
setBuildingData(building);
|
2021-02-24 02:48:09 -05:00
|
|
|
}
|
|
|
|
}, []);
|
|
|
|
|
2021-02-22 01:59:24 -05:00
|
|
|
useEffect(() => {
|
|
|
|
return () => {
|
|
|
|
setIsOld(true);
|
|
|
|
};
|
|
|
|
}, [buildingId]);
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
if(isOld) {
|
|
|
|
fetchData();
|
|
|
|
}
|
|
|
|
}, [isOld]);
|
|
|
|
|
|
|
|
const reloadData = useCallback(() => setIsOld(true), []);
|
|
|
|
|
2021-02-24 02:48:09 -05:00
|
|
|
return [buildingData, updateData, reloadData];
|
2021-02-22 01:59:24 -05:00
|
|
|
}
|