qotnews/webclient/src/Feed.js

80 lines
1.7 KiB
JavaScript
Raw Normal View History

2019-08-24 05:04:51 +00:00
import React from 'react';
import { Link } from 'react-router-dom';
import { Helmet } from 'react-helmet';
import { siteLogo, sourceLink, infoLine } from './utils.js';
import { clearStorage } from './utils.js';
2019-08-24 05:04:51 +00:00
class Feed extends React.Component {
constructor(props) {
super(props);
this.state = {
stories: JSON.parse(localStorage.getItem('stories')) || false,
error: false,
};
}
2019-10-12 05:32:17 +00:00
componentDidMount() {
fetch('/api')
.then(res => res.json())
.then(
(result) => {
this.setState({ stories: result.stories });
clearStorage();
2019-10-12 05:32:17 +00:00
localStorage.setItem('stories', JSON.stringify(result.stories));
result.stories.filter(x => x.score >= 20).slice(0, 25).forEach(x => {
fetch('/api/' + x.id)
2019-08-24 05:04:51 +00:00
.then(res => res.json())
.then(result => {
localStorage.setItem(x.id, JSON.stringify(result.story));
console.log('Preloaded story', x.id, x.title);
}, error => {}
);
});
2019-10-12 05:32:17 +00:00
},
(error) => {
this.setState({ error: true });
}
);
2019-08-24 05:04:51 +00:00
}
render() {
const stories = this.state.stories;
const error = this.state.error;
return (
<div className='container'>
<Helmet>
<title>Feed - QotNews</title>
</Helmet>
{error && <p>Connection error?</p>}
{stories ?
2019-08-24 05:04:51 +00:00
<div>
{stories.map((x, i) =>
2019-10-12 05:32:17 +00:00
<div className='item' key={i}>
<div className='num'>
{i+1}.
</div>
2019-08-24 05:04:51 +00:00
<div className='title'>
<Link className='link' to={'/' + x.id}>{siteLogo[x.source]} {x.title}</Link>
2019-08-24 05:04:51 +00:00
<span className='source'>
&#8203;({sourceLink(x)})
</span>
</div>
2019-08-24 05:04:51 +00:00
{infoLine(x)}
2019-08-24 05:04:51 +00:00
</div>
)}
2019-08-24 05:04:51 +00:00
</div>
:
<p>loading...</p>
2019-08-24 05:04:51 +00:00
}
</div>
);
}
}
export default Feed;