Cache articles in memory for speed

This commit is contained in:
Tanner Collin 2019-10-18 21:26:22 +00:00
parent 6764bf0d6d
commit 187c6b8110
4 changed files with 33 additions and 6 deletions

View File

@ -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>

View File

@ -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,
};
}

View File

@ -10,8 +10,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,
};
}

View File

@ -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 => {}
);
});