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

View File

@@ -21,5 +21,6 @@
"not dead", "not dead",
"not ie <= 11", "not ie <= 11",
"not op_mini all" "not op_mini all"
] ],
"proxy": "http://localhost:5000"
} }

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

@@ -3,39 +3,67 @@ import logo from './logo.svg';
import './App.css'; import './App.css';
class App extends Component { 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() { render() {
return ( return (
<div className="App"> <div className="App">
<header className="App-header"> <header className="App-header">
<img src={logo} className="App-logo" alt="logo" /> <img src={logo} className="App-logo" alt="logo" />
{ process.env.NODE_ENV === 'production' ? { process.env.NODE_ENV === 'production' ?
<p> <p>
This is a production build from create-react-app 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>
</p> </p>
: <p> : <p>
Edit <code>src/App.js</code> and save to reload. 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>
} }
<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> </header>
</div> </div>
); );

View File

@@ -12,3 +12,7 @@ code {
font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New", font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
monospace; monospace;
} }
p + p {
margin-top: 0;
}