Created
January 3, 2018 16:04
-
-
Save fpersico/8cc26355bc5a0f186cabbca737175745 to your computer and use it in GitHub Desktop.
Home screen
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react'; | |
import { Container, Row, Col } from 'reactstrap'; | |
import { fetchArticles } from '../api'; | |
import ArticleList from '../components/ArticleList'; | |
import SimplePager from '../components/SimplePager'; | |
class HomeScreen extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
articles: null, | |
page: 1, | |
more: false | |
}; | |
} | |
componentDidMount() { | |
this.loadArticles(); | |
} | |
render() { | |
const { page, more, error, errorMessage, articles } = this.state; | |
return ( | |
<Container> | |
<Row> | |
<Col> | |
{error && <h2>{errorMessage}</h2>} | |
{articles && ( | |
<div> | |
<SimplePager | |
page={page} | |
hasNext={more} | |
onChange={this.handlePagerChange} | |
/> | |
<ArticleList articles={articles} /> | |
<SimplePager | |
page={page} | |
hasNext={more} | |
onChange={this.handlePagerChange} | |
/> | |
</div> | |
)} | |
</Col> | |
</Row> | |
</Container> | |
); | |
} | |
loadArticles = () => { | |
const { page } = this.state; | |
fetchArticles(page) | |
.then(response => { | |
const body = response.body; | |
const articles = body.data; | |
const more = body.links.hasOwnProperty('next'); | |
this.setState({ | |
error: false, | |
articles: articles, | |
more: more | |
}); | |
window.scrollTo(0, 0); | |
}) | |
.catch(error => { | |
this.setState({ | |
error: true, | |
errorMessage: `Error fetching articles: '${error.message}'` | |
}); | |
}); | |
}; | |
handlePagerChange = newPage => { | |
this.setState( | |
{ | |
page: newPage | |
}, | |
this.loadArticles | |
); | |
}; | |
} | |
export default HomeScreen; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment