Fetch Articles from JSON blob

This commit is contained in:
Nick Pegg 2017-10-07 12:08:50 -07:00
parent 1554308f8a
commit 0968c22cf6
2 changed files with 79 additions and 22 deletions

View file

@ -38,7 +38,7 @@ class App extends Component {
{ /* Article routes */ } { /* Article routes */ }
<Route path="/page/:page" component={Articles} /> <Route path="/page/:page" component={Articles} />
<Route path="/:year/:month/:title.html" component={RoutedArticle} /> <Route path="/:year/:month/:title" component={RoutedArticle} />
{ /* 404 fallback */ } { /* 404 fallback */ }
<Route component={FourOhFour} /> <Route component={FourOhFour} />

View file

@ -63,29 +63,86 @@ class Article extends Component {
} }
} }
// Goofball article for routing testing
class RoutedArticle extends Component {
constructor(props) {
super(props);
this.props = props;
this.params = props.match.params;
const RoutedArticle = ({match}) => ( this.state = {
<Article title={match.params.title} /> body: '',
) title: 'default title',
date: 'default date',
tags: [],
}
}
render() {
return (
<Article title={this.state.title} date={this.state.date} />
)
}
}
const Articles = ({match}) => ( class Articles extends Component {
// TODO: This is the thing that'll fetch the articles from the JSON blob constructor(props) {
// based on the URL that's hit. This will return one or more Articles super(props);
<div>
<Article // Number of Articles per page
title="This is where a blog post would go" // TODO: Pull this from a configuration somehow
date="1970-01-01" this.per_page = 5;
/>
<Article this.params = props.match.params;
title="This is another blog post!" this.state = {
date="1970-01-01" articles: [],
is_page }
/>
<p> console.log("page", this.params.page);
This is page number: {match.params.page} }
</p>
</div> fetchArticles() {
) // Fetch articles from JSON blob
fetch('/site.json')
.then((resp) => resp.json())
.then((blob) => {
let offset = 0;
if (this.params.page) {
offset = this.params.page * this.per_page;
}
console.log("offset", offset);
let posts = blob.posts.slice(offset, offset + this.per_page);
this.setState({articles: posts});
})
.catch(function(error) {
console.log("Oh no! " + error);
});
}
componentDidMount() {
this.fetchArticles();
}
componentWillReceiveProps(props) {
this.params = props.match.params;
this.fetchArticles();
}
render() {
return (
<div>
{this.state.articles.map(article =>
<Article
key={article.title}
title={article.title}
date="1970-01-01"
/>
)}
</div>
)
}
}
export { Article, Articles, RoutedArticle }; export { Article, Articles, RoutedArticle };