From 65fd0a393bf03dabbb2192aa39768794b251c8f2 Mon Sep 17 00:00:00 2001 From: Mars Hall Date: Sun, 16 Dec 2018 11:57:34 -0800 Subject: [PATCH] Re-implement Node API example in React app --- react-ui/package.json | 3 +- react-ui/src/App.js | 70 +++++++++++++++++++++++++++++------------- react-ui/src/index.css | 4 +++ 3 files changed, 55 insertions(+), 22 deletions(-) diff --git a/react-ui/package.json b/react-ui/package.json index b5056c2..6bedcc5 100644 --- a/react-ui/package.json +++ b/react-ui/package.json @@ -21,5 +21,6 @@ "not dead", "not ie <= 11", "not op_mini all" - ] + ], + "proxy": "http://localhost:5000" } diff --git a/react-ui/src/App.js b/react-ui/src/App.js index 4e182e5..4722bc9 100644 --- a/react-ui/src/App.js +++ b/react-ui/src/App.js @@ -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 (
logo { process.env.NODE_ENV === 'production' ? -

- This is a production build from create-react-app -
-
- - React + Node deployment on Heroku - + This is a production build from create-react-app.

- :

Edit src/App.js and save to reload. -
-
- - Learn React -

} +

{'« '} + {this.state.fetching + ? 'Fetching message from API' + : this.state.message} + {' »'}

+

+ React + Node deployment on Heroku +

+

+ Learn React +

); diff --git a/react-ui/src/index.css b/react-ui/src/index.css index cee5f34..2b657c2 100644 --- a/react-ui/src/index.css +++ b/react-ui/src/index.css @@ -12,3 +12,7 @@ code { font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New", monospace; } + +p + p { + margin-top: 0; +}