refactor: Refactor Feed component to functional with hooks
This commit is contained in:
@@ -1,28 +1,22 @@
|
|||||||
import React from 'react';
|
import React, { useState, useEffect } from 'react';
|
||||||
import { Link } from 'react-router-dom';
|
import { Link } from 'react-router-dom';
|
||||||
import { Helmet } from 'react-helmet';
|
import { Helmet } from 'react-helmet';
|
||||||
import localForage from 'localforage';
|
import localForage from 'localforage';
|
||||||
import { sourceLink, infoLine, logos } from './utils.js';
|
import { sourceLink, infoLine, logos } from './utils.js';
|
||||||
|
|
||||||
class Feed extends React.Component {
|
function Feed({ updateCache }) {
|
||||||
constructor(props) {
|
const [stories, setStories] = useState(() => JSON.parse(localStorage.getItem('stories')) || false);
|
||||||
super(props);
|
const [error, setError] = useState(false);
|
||||||
|
|
||||||
this.state = {
|
useEffect(() => {
|
||||||
stories: JSON.parse(localStorage.getItem('stories')) || false,
|
|
||||||
error: false,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
componentDidMount() {
|
|
||||||
fetch('/api')
|
fetch('/api')
|
||||||
.then(res => res.json())
|
.then(res => res.json())
|
||||||
.then(
|
.then(
|
||||||
(result) => {
|
(result) => {
|
||||||
const updated = !this.state.stories || this.state.stories[0].id !== result.stories[0].id;
|
const updated = !stories || stories[0].id !== result.stories[0].id;
|
||||||
console.log('updated:', updated);
|
console.log('updated:', updated);
|
||||||
|
|
||||||
this.setState({ stories: result.stories });
|
setStories(result.stories);
|
||||||
localStorage.setItem('stories', JSON.stringify(result.stories));
|
localStorage.setItem('stories', JSON.stringify(result.stories));
|
||||||
|
|
||||||
if (updated) {
|
if (updated) {
|
||||||
@@ -33,21 +27,17 @@ class Feed extends React.Component {
|
|||||||
.then(result => {
|
.then(result => {
|
||||||
localForage.setItem(x.id, result.story)
|
localForage.setItem(x.id, result.story)
|
||||||
.then(console.log('preloaded', x.id, x.title));
|
.then(console.log('preloaded', x.id, x.title));
|
||||||
this.props.updateCache(x.id, result.story);
|
updateCache(x.id, result.story);
|
||||||
}, error => {}
|
}, error => {}
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
(error) => {
|
(error) => {
|
||||||
this.setState({ error: true });
|
setError(true);
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
}, [updateCache]);
|
||||||
|
|
||||||
render() {
|
|
||||||
const stories = this.state.stories;
|
|
||||||
const error = this.state.error;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className='container'>
|
<div className='container'>
|
||||||
@@ -80,6 +70,5 @@ class Feed extends React.Component {
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
export default Feed;
|
export default Feed;
|
||||||
|
|||||||
Reference in New Issue
Block a user