Cache articles in memory for speed

master
Tanner Collin 5 years ago
parent 6764bf0d6d
commit 187c6b8110
  1. 22
      webclient/src/App.js
  2. 7
      webclient/src/Article.js
  3. 9
      webclient/src/Comments.js
  4. 1
      webclient/src/Feed.js

@ -1,5 +1,6 @@
import React from 'react';
import { BrowserRouter as Router, Route, Link, Switch } from 'react-router-dom';
import localForage from 'localforage';
import './Style-light.css';
import './Style-dark.css';
import './fonts/Fonts.css';
@ -17,6 +18,12 @@ class App extends React.Component {
this.state = {
theme: localStorage.getItem('theme') || '',
};
this.cache = {};
}
updateCache = (key, value) => {
this.cache[key] = value;
}
light() {
@ -29,6 +36,15 @@ class App extends React.Component {
localStorage.setItem('theme', 'dark');
}
componentDidMount() {
if (!this.cache.length) {
localForage.iterate((value, key) => {
this.updateCache(key, value);
});
console.log('loaded cache from localforage');
}
}
render() {
const theme = this.state.theme;
document.body.style.backgroundColor = theme === 'dark' ? '#000' : '#eeeeee';
@ -46,12 +62,12 @@ class App extends React.Component {
<Route path='/(|search)' component={Search} />
</div>
<Route path='/' exact component={Feed} />
<Route path='/' exact render={(props) => <Feed {...props} updateCache={this.updateCache} />} />
<Switch>
<Route path='/search' component={Results} />
<Route path='/:id' exact component={Article} />
<Route path='/:id' exact render={(props) => <Article {...props} cache={this.cache} />} />
</Switch>
<Route path='/:id/c' exact component={Comments} />
<Route path='/:id/c' exact render={(props) => <Comments {...props} cache={this.cache} />} />
<ScrollToTop />
</Router>

@ -8,8 +8,13 @@ class Article extends React.Component {
constructor(props) {
super(props);
const id = this.props.match.params.id;
const cache = this.props.cache;
if (id in cache) console.log('cache hit');
this.state = {
story: false,
story: cache[id] || false,
error: false,
};
}

@ -10,12 +10,17 @@ class Article extends React.Component {
constructor(props) {
super(props);
const id = this.props.match.params.id;
const cache = this.props.cache;
if (id in cache) console.log('cache hit');
this.state = {
story: false,
story: cache[id] || false,
error: false,
};
}
componentDidMount() {
const id = this.props.match.params.id;

@ -33,6 +33,7 @@ class Feed extends React.Component {
.then(result => {
localForage.setItem(x.id, result.story)
.then(console.log('preloaded', x.id, x.title));
this.props.updateCache(x.id, result.story);
}, error => {}
);
});

Loading…
Cancel
Save