import { useCallback , useEffect , useState } from 'react' ; import { Building , BuildingAttributeVerificationCounts } from '../models/building' ; import { apiGet } from '../apiHelpers' ; param buildingId param preloadedData param includeUserAttributes returns export function useBuildingData ( buildingId , preloadedData , includeUserAttributes = false ) { 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 { let [ building , buildingUprns ] = await Promise . all ( [ apiGet ( `/api/buildings/${ buildingId }.json${ includeUserAttributes ? '?user_attributes=true' : '' }` ) , apiGet ( `/api/buildings/${ buildingId }/uprns.json` ) ] ) ; building . uprns = buildingUprns . uprns ; building = Object . assign ( building , { ... building . user_attributes } ) ; delete building . user_attributes ; setBuildingData ( building ) ; } catch ( error ) { console . error ( error ) ; } setIsOld ( false ) ; } , [ buildingId ] ) ; const updateData = useCallback ( ( building ) => { if ( building == undefined ) { setBuildingData ( building ) ; } else { if ( building . verified == undefined ) { building . verified = { } as BuildingAttributeVerificationCounts ; } setBuildingData ( building ) ; } } , [ ] ) ; useEffect ( ( ) => { return ( ) => { setIsOld ( true ) ; } ; } , [ buildingId ] ) ; useEffect ( ( ) => { if ( isOld ) { fetchData ( ) ; } } , [ isOld ] ) ; const reloadData = useCallback ( ( ) => setIsOld ( true ) , [ ] ) ; return [ buildingData , updateData , reloadData ] ; }