In Postman, create a GET
request to the following URL:
In the next step we will be making the same API request from our React app, using axios
.
After that, you will have a chance to create your own API with the same route.
Create a new React app using npx create-react-app
and update the App.js
as per the code below.
You will notice that the API call is in the componentDidMount
lifecycle method, because if we would have updated the state inside the render()
method, we would have run into an infinite render loop.
Here you can find brief explanation on how render()
lifecycle method works reactjs - render()
.
As we will be using axios
to make the request to the API make sure to install the dependency via npm install axios --save
/
src/App.js
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import axios from 'axios';
class App extends Component {
constructor(){
super()
this.state = {
countries: []
}
}
componentDidMount() {
axios.get("http://206.189.7.127/countries/")
.then(response => {
this.setState({countries: response.data})
})
};
render() {
return (
<div className="App">
{this.state.countries.map(country => <h1>{country.name.common}</h1>)}
</div>
);
}
}
export default App;
You already know this step. Set up a simple express
app with the following route:
app.get('/countries', (req, res, next) => {
const countries = require("./countries.json")
res.json(countries);
});
The rest of the express you have to set up yourself. In case you’re in dire need of a reminder, check out this repo . Don’t forget to put the countries.json
file in the right directory. Now if you go to localhost:3000/countries
, you should get back all the countries.
How you will search for a particular country, is left up to you.
Okay, so you have the back-end and the front-end. Nice, we’re back. So how do you connect them? It’s surprisingly easy. Spin up your express API and update App.js
code with this:
// src/App.js
componentDidMount() {
axios.get("http://localhost:3000/countries")
.then(response => {
this.setState({countries: response.data})
})
}