From a02bcd8c27a632071686d3487c0ad0800f98a8fe Mon Sep 17 00:00:00 2001 From: Maciej Ziarkowski Date: Thu, 14 Nov 2019 15:25:19 +0000 Subject: [PATCH] Fetch data when opening building page without SSR --- app/src/frontend/map-app.tsx | 49 ++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/app/src/frontend/map-app.tsx b/app/src/frontend/map-app.tsx index 71a61db4..e9b698ce 100644 --- a/app/src/frontend/map-app.tsx +++ b/app/src/frontend/map-app.tsx @@ -2,6 +2,8 @@ import { parse } from 'query-string'; import React, { Fragment } from 'react'; import { Redirect, Route, RouteComponentProps, Switch } from 'react-router-dom'; +import { strictParseInt } from '../parse'; + import BuildingView from './building/building-view'; import Categories from './building/categories'; import { EditHistory } from './building/edit-history/edit-history'; @@ -56,6 +58,7 @@ class MapApp extends React.Component { componentDidMount() { this.fetchLatestRevision(); + this.fetchBuildingData(); } async fetchLatestRevision() { @@ -75,6 +78,52 @@ class MapApp extends React.Component { } } + /** + * Fetches building data if a building is selected but no data provided through + * props (from server-side rendering) + */ + async fetchBuildingData() { + if(this.props.match.params.building != undefined && this.props.building == undefined) { + try { + // TODO: simplify API calls, create helpers for fetching data + const buildingId = strictParseInt(this.props.match.params.building); + let [building, building_uprns, building_like] = await Promise.all([ + fetch(`/api/buildings/${buildingId}.json`, { + method: 'GET', + headers: { + 'Content-Type': 'application/json' + }, + credentials: 'same-origin' + }).then(res => res.json()), + fetch(`/api/buildings/${buildingId}/uprns.json`, { + method: 'GET', + headers: { + 'Content-Type': 'application/json' + }, + credentials: 'same-origin' + }).then(res => res.json()), + fetch(`/api/buildings/${buildingId}/like.json`, { + method: 'GET', + headers: { + 'Content-Type': 'application/json' + }, + credentials: 'same-origin' + }).then(res => res.json()) + ]); + + building.uprns = building_uprns.uprns; + + this.setState({ + building: building, + building_like: building_like.like + }); + } catch(error) { + console.error(error); + // TODO: add UI for API errors + } + } + } + getCategory(category: string) { if (category === 'categories') return undefined;