From 19943a28eb2ac40d1ad3bc0de8ee432447654cb4 Mon Sep 17 00:00:00 2001 From: Janne Alatalo <janne.alatalo@jamk.fi> Date: Mon, 24 Sep 2018 16:39:10 +0300 Subject: [PATCH] Fix race condition in data fetching --- src/App.js | 11 ++--------- src/utils/api-client.js | 10 +++++++--- 2 files changed, 9 insertions(+), 12 deletions(-) diff --git a/src/App.js b/src/App.js index e3558c4..651dfb8 100644 --- a/src/App.js +++ b/src/App.js @@ -3,16 +3,10 @@ import { Map } from 'immutable'; import PointMap from './PointMap.js'; import './App.css'; -import { get_lam_points, connect_lam_ws, get_lam_station_data } from './utils/api-client.js'; +import { get_lam_points, connect_lam_ws } from './utils/api-client.js'; class App extends Component { - set_lam_points(lam_points) { - this.setState((prevState) => { - return { ...prevState, lam_points }; - }); - } - update_state(fn) { this.setState((prevState) => { return fn(prevState); @@ -33,8 +27,7 @@ class App extends Component { let width = window.innerWidth; let height = window.innerHeight; this.state = { lam_points: Map(), mapSize: { width, height } }; - get_lam_points("http://tie.digitraffic.fi", this.set_lam_points.bind(this)); - get_lam_station_data("http://tie.digitraffic.fi", this.update_state.bind(this)); + get_lam_points("http://tie.digitraffic.fi", this.update_state.bind(this)); connect_lam_ws("ws://tie.digitraffic.fi", this.update_state.bind(this)); this.handleResize = this.handleResize.bind(this); } diff --git a/src/utils/api-client.js b/src/utils/api-client.js index 02917a6..aae2d79 100644 --- a/src/utils/api-client.js +++ b/src/utils/api-client.js @@ -3,7 +3,7 @@ import { Map } from 'immutable'; import LamStation from './lam-station.js'; export function get_lam_points(api_url, set_state) { - fetch(`${api_url}/api/v1/metadata/tms-stations`) + return fetch(`${api_url}/api/v1/metadata/tms-stations`) .then((res) => res.json()) .then((json) => { let stations = Map(); @@ -13,13 +13,17 @@ export function get_lam_points(api_url, set_state) { let station = new LamStation(id, coordinates, 0, 0); stations = stations.set(id, station); } - set_state(stations); + set_state((prevState) => { + const lam_points = stations; + return { ...prevState, lam_points }; + }); }) + .then(() => get_lam_station_data(api_url, set_state)) .catch(e => (console.error(e))); } export function get_lam_station_data(api_url, set_state) { - fetch(`${api_url}/api/v1/data/tms-data`) + return fetch(`${api_url}/api/v1/data/tms-data`) .then((res) => res.json()) .then((json) => { set_state((prevState) => { -- GitLab