From 3fd2a6cd665e65596385402f730ce9f20796cf27 Mon Sep 17 00:00:00 2001 From: Michael Jackson Date: Mon, 14 Jan 2019 18:41:32 -0800 Subject: [PATCH] Show stats on initial render if they are cached --- modules/client/main/App.js | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/modules/client/main/App.js b/modules/client/main/App.js index 491d615..6f3b902 100644 --- a/modules/client/main/App.js +++ b/modules/client/main/App.js @@ -93,22 +93,29 @@ function Stats({ data }) { } export default class App extends React.Component { - state = { stats: null }; + constructor(props) { + super(props); + + this.state = { stats: null }; + + if (typeof window === 'object' && window.localStorage) { + const savedStats = window.localStorage.savedStats; + + if (savedStats) { + this.state.stats = JSON.parse(savedStats); + } + + window.onbeforeunload = () => { + window.localStorage.savedStats = JSON.stringify(this.state.stats); + }; + } + } componentDidMount() { + // Refresh latest stats. fetch('/api/stats?period=last-month') .then(res => res.json()) .then(stats => this.setState({ stats })); - - if (window.localStorage) { - const savedStats = window.localStorage.savedStats; - - if (savedStats) this.setState({ stats: JSON.parse(savedStats) }); - - window.onbeforeunload = () => { - localStorage.savedStats = JSON.stringify(this.state.stats); - }; - } } render() {