Re-implement Node API example in React app

This commit is contained in:
Mars Hall
2018-12-16 11:57:34 -08:00
parent d261bdfb76
commit 65fd0a393b
3 changed files with 55 additions and 22 deletions

70
react-ui/src/App.js vendored
View File

@@ -3,39 +3,67 @@ import logo from './logo.svg';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
message: null,
fetching: true
};
}
componentDidMount() {
fetch('/api')
.then(response => {
if (!response.ok) {
throw new Error(`status ${response.status}`);
}
return response.json();
})
.then(json => {
this.setState({
message: json.message,
fetching: false
});
}).catch(e => {
this.setState({
message: `API call failed: ${e}`,
fetching: false
});
})
}
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
{ process.env.NODE_ENV === 'production' ?
<p>
This is a production build from create-react-app
<br/>
<br/>
<a
className="App-link"
href="https://github.com/mars/heroku-cra-node"
>
React + Node deployment on Heroku
</a>
This is a production build from create-react-app.
</p>
: <p>
Edit <code>src/App.js</code> and save to reload.
<br/>
<br/>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</p>
}
<p>{'« '}<strong>
{this.state.fetching
? 'Fetching message from API'
: this.state.message}
</strong>{' »'}</p>
<p><a
className="App-link"
href="https://github.com/mars/heroku-cra-node"
>
React + Node deployment on Heroku
</a></p>
<p><a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a></p>
</header>
</div>
);