Created
April 25, 2017 18:18
-
-
Save kepford/a582e0338de426d24c47e616dc737c2a to your computer and use it in GitHub Desktop.
This file contains 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 Header from './Header.js'; | |
import Article from './Article'; | |
import sampleArticles from '../sample-articles'; | |
import '../css/App.css'; | |
class App extends Component { | |
constructor() { | |
super(); | |
this.loadArticles = this.loadArticles.bind(this); | |
this.fetchArticles = this.fetchArticles.bind(this); | |
// getinitialState | |
this.state = { | |
articles: {} | |
}; | |
} | |
// Load sample articles. | |
loadArticles() { | |
this.setState({ | |
articles: sampleArticles | |
}); | |
} | |
fetchArticles() { | |
const request = new XMLHttpRequest(); | |
request.open('GET', 'http://mcdemo.mcdev/api/v1/mcdemo', true); | |
request.onload = () => { | |
if (request.status >= 200 && request.status < 400) { | |
this.setState({ | |
articles: JSON.parse(request.responseText) | |
}) | |
console.log(this); | |
} | |
else { | |
// We reached our target server, but it returned an error | |
console.log(request.status); | |
} | |
}; | |
request.onerror = function () { | |
// There was a connection error of some sort | |
}; | |
request.send(); | |
} | |
componentWillMount() { | |
// This runs right before the <App> is rendered. | |
fetchArticles(); | |
} | |
render() { | |
return ( | |
<div className="App"> | |
<Header | |
appName="Mediacurrent JS React Demo" | |
appIntro="An experiment using Drupal's REST endpoint to display a list of blog posts." | |
/> | |
<div className="articles"> | |
<h2>A list of Articles</h2> | |
<button onClick={this.fetchArticles}>Load REST Articles</button> | |
<button onClick={this.loadArticles}>Load local Articles</button> | |
{ | |
Object | |
.keys(this.state.articles) | |
.map(key => <Article key={key} details={this.state.articles[key]} />) | |
} | |
</div> | |
</div> | |
); | |
} | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment