Practical examples

We will go through two examples of using some open REST APIs. First, we will make a React app that shows the current weather in London. The weather is fetched from OpenWeatherMap (https://openweathermap.org/). You need to register to OpenWeatherMap to get an API key. We will use a free account as that is enough for our needs. When you have registered, navigate to your account info to find the API keys tab. There you'll see the API key that you need for your React weather app:

Let's create a new React app with create-react-app. Open the PowerShell or other terminal you are using, and type the following command:

create-react-app weatherapp

Move to the weatherApp folder:

cd weatherapp

Start your app with the following command:

npm start

Open your project folder with the VS Code and open the App.js file in the editor view. Remove all code inside the <div className="App"></div> divider. Now your source code should look like the following:

import React, { Component } from 'react';
import './App.css';

class App extends Component {
render() {
return (
<div className="App">
</div>
);
}
}

export default App;
If you have installed Reactjs code snippets to VS Code, you can create a default constructor automatically by typing con. There are lots of different shortcuts for typical React methods, such as cdm for componentDidMount().

First, we add a necessary constructor and state. We will show the temperature, description, and weather icon in our app, therefore, we define three state values. We will also add one Boolean state to indicate the status of fetch loading. The following is the source code of the constructor:

  constructor(props) {
super(props);
this.state = {temp: 0, desc: '', icon: '', loading: true}
}

When you are using a REST API, you should first inspect the response to be able to get values from the JSON data. In the following example, you can see the address that returns the current weather for London. Copy the address to a browser and you can see the JSON response data:

api.openweathermap.org/data/2.5/weather?q=London&units=Metric&APIkey=YOUR_KEY

From the response, you can see that the temp can be accessed using main.temp. The description and icon are inside the weather array, which has only one element and we can access it using weather[0].description and weather[0].icon:

The REST API call is done with the fetch in the componentDidMount() life cycle method. After the successful response, we save the weather data to the state and change the loading state to false. After the state has been changed, the component will be re-rendered. We will implement the render() method in the next step. The following is the source code of the componentDidMount() method:

  componentDidMount() {
fetch('http://api.openweathermap.org/data/2.5/weather?
q=London&units=Metric
&APIkey=c36b03a963176b9a639859e6cf279299')
.then(response => response.json())
.then(responseData => {
this.setState({
temp: responseData.main.temp,
desc: responseData.weather[0].description,
icon: responseData.weather[0].icon,
loading: false
})
})
.catch(err => console.error(err));
}

After you have added the componentDidMount() method, the request is done when the component is mounted. We can check that everything is done correctly using the React Developer Tool. Open your app in a browser and open your browser developer tool's React tab. Now you can see that the state is updated with the values from the response. You can also check from the Network tab that the request status is 200 OK:

Finally, we implement the render() method to show weather values. We are using conditional rendering, otherwise, we get an error because we don't have image code in the first render call and image upload won't succeed. To show the weather icon, we have to add http://openweathermap.org/img/w/ before the icon code and .png after the icon code. Then, we can set the concatenated image URL to the img element's src attribute. The temperature and description are shown in the paragraph element. The °C  HTML entity shows the Celsius degrees symbol:

  render() {
const imgSrc = `http://openweathermap.org/img/w/${this.state.icon}.png`;

if (this.state.loading) {
return <p>Loading</p>;
}
else {
return (
<div className="App">
<p>Temperature: {this.state.temp} °C</p>
<p>Description: {this.state.desc}</p>
<img src={imgSrc} alt="Weather icon" />
</div>
);
}
}

Now your app should be ready. When you open it in a browser, it should look like the following image:

The source code of the whole App.js file looks as follows:

import React, { Component } from 'react';
import './App.css';

class App extends Component {
constructor(props) {
super(props);
this.state = {temp: 0, desc: '', icon: ''}
}

componentDidMount() {
fetch('http://api.openweathermap.org/data/2.5/weather?
q=London&units=Metric&APIkey=YOUR_KEY')
.then(response => response.json())
.then(responseData => {
this.setState({
temp: responseData.main.temp,
desc: responseData.weather[0].description,
icon: responseData.weather[0].icon
});
});
}

render() {
const imgSrc = 'http://openweathermap.org/img/w/' +
this.state.icon + '.png';

    return (
<div className="App">
<p>Temperature: {this.state.temp}</p>
<p>Description: {this.state.desc}</p>
<img src={imgSrc} />
</div>
);
}
}

export default App;

In this second example, we are going to use the GitHub API to fetch repositories by a keyword. With the same steps as in the previous example, create a new React app called restgithub. Start the app and open the project folder with the VS Code.

Remove the extra code inside the <div className="App"></div> divider from the App.js file and again your App.js code should look like the following sample code:

import React, { Component } from 'react';
import './App.css';

class App extends Component {
render() {
return (
<div className="App">
</div>
);
}
}

export default App;

The URL of the GitHub REST API is the following:

https://api.github.com/search/repositories?q=KEYWORD

Let's inspect the JSON response by typing the URL into a browser and using the react keyword. From the response, we can see that repositories are returned as a JSON array called items. From the individual repositories, we will show the full_name and html_url values. We will present the data in the table and use the map function to transform the values to table rows, as shown in the previous chapter:

We are going to make the REST API call with the keyword from the user input. Therefore, we can't make the REST API call in the componentDidMount() method because, in that phase, we don't have the user input available. One way to implement this is to create an input field and button. The user types the keyword into the input field and the REST API call is done when the button is pressed. We need two states, one for the user input and one for the data from the JSON response. The following is the source code of the constructor. The type of data state is an array because repositories are returned as JSON arrays in the response:

  constructor(props) {
super(props);
this.state = { keyword: '', data: [] };
}

Next, we implement the input field and the button into the render() method. We also have to add a change listener to our input field to be able to save the input value to the state, called keyword. The button has a click listener that invokes the function that will do the REST API call with the given keyword:

  fetchData = () => {
// REST API call comes here
}

handleChange = (e) => {
this.setState({keyword: e.target.value});
}

render() {
return (
<div className="App">
<input type="text" onChange={this.handleChange} />
<button onClick={this.fetchData} value={this.state.keyword} >Fetch</button>
</div>
);
}

In the fetchData function, we concatenate the url and keyword state by using template literals. Then we save the items array from the response to the state, called data. The following is the source code of the fetchData function:

  fetchData = () => {
const url = `https://api.github.com/search/repositories?
q=${this.state.keyword}`;
fetch(url)
.then(response => response.json())
.then(responseData => {
this.setState({data : responseData.items });
});
}

In the render method, we first use the map function to transform the data state to table rows. The url repository will be the href of the link element:

  render() {
const tableRows = this.state.data.map((item, index) =>
<tr key={index}><td>{item.full_name}</td>
<td><a href={item.html_url}>{item.html_url}</a></td></tr>);

return (
<div className="App">
<input type="text" onChange={this.handleChange} />
<button onClick={this.fetchData} value={this.state.keyword} >Fetch</button>
<table><tbody>{tableRows}</tbody></table>
</div>
);

The following screenshot shows the final app when using the React keyword in the REST API call:

The source code of the whole App.js file looks like the following:

import React, { Component } from 'react';
import './App.css';

class App extends Component {
constructor(props) {
super(props);
this.state = { keyword: '', data: [] };
}

fetchData = () => {
const url = `https://api.github.com/search/repositories?
q=${this.state.keyword}`;
fetch(url)
.then(response => response.json())
.then(responseData => {
this.setState({data : responseData.items });
});
}

handleChange = (e) => {
this.setState({keyword: e.target.value});
}

render() {
const tableRows = this.state.data.map((item, index) =>
<tr key={index}><td>{item.full_name}</td>
<td><a href={item.html_url}>{item.html_url}</a></td></tr>);

return (
<div className="App">
<input type="text" onChange={this.handleChange} />
<button onClick={this.fetchData}
value={this.state.keyword} >Fetch</button>
<table><tbody>{tableRows}</tbody></table>
</div>
);
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.88.54