Reader small image

You're reading from  Full Stack Development with Spring Boot and React - Third Edition

Product typeBook
Published inApr 2022
Reading LevelIntermediate
PublisherPackt
ISBN-139781801816786
Edition3rd Edition
Languages
Right arrow
Author (1)
Juha Hinkula
Juha Hinkula
author image
Juha Hinkula

Juha Hinkula is a software development lecturer at Haaga-Helia University of Applied Sciences in Finland. He received an MSc degree in Computer Science from the University of Helsinki and he has over 17 years of industry experience in software development. Over the past few years, he has focused on modern full stack development. He is also a passionate mobile developer with Android-native technology, and also uses React Native.
Read more about Juha Hinkula

Right arrow

Chapter 8: Consuming the REST API with React

This chapter explains networking with React. That is really important skill which we need in most of the React apps. We will learn about promises, which make asynchronous code cleaner and more readable. For networking, we will use the fetch and axios libraries. As an example, we will use the GitHub REST API to demonstrate how to consume RESTful web services with React.

In this chapter, we will cover the following topics:

  • Using promises
  • Using the fetch API
  • Using the axios library
  • Practical examples
  • Handling responses from the REST API

Technical requirements

In this book, we are using the Windows operating system, but all the tools are available for Linux and macOS via Node.js.

The following GitHub link will also be required: https://github.com/PacktPublishing/Full-Stack-Development-with-Spring-Boot-and-React/tree/main/Chapter08.

Using promises

The traditional way to handle an asynchronous operation is to use callback functions for the success or failure of the operation. One of these callback functions is called (success or failure), depending on the result of the call. The following example shows the idea of using a callback function:

function doAsyncCall(success,  failure)  {
  // Do some API call 
  if (SUCCEED)
    success(resp);
  else
    failure(err);
}
success(response) {
  // Do something with response
}
failure(error) {
  // Handle error
}
doAsyncCall(success, failure);

A promise is an object that represents the result of an asynchronous operation. The use of promises simplifies the code when you're executing asynchronous calls. Promises are non-blocking.

A promise can be in one of three states:

  • Pending: Initial state
  • Fulfilled: Successful operation
  • Rejected...

Using the fetch API

With the fetch API, you can make web requests. The idea of the fetch API is similar to the traditional XMLHttpRequest, but the fetch API also supports promises, which makes it more straightforward to use. You don't have to install any libraries if you are using fetch.

The fetch API provides a fetch() method that has one mandatory argument: the path of the resource you are calling. In the case of a web request, it will be the URL of the service. For a simple GET method call, which returns a JSON response, the syntax is as follows. The fetch() method returns a promise that contains the response. You can use the json() method to parse the JSON body from the response:

fetch('http://someapi.com')
.then(response => response.json())
.then(data => console.log(data));
.catch(error => console.error(error))

To use another HTTP method, such as POST, you must define it in the second argument of the fetch() method. The second argument is an object...

Using the axios library

You can also use other libraries for network calls. One very popular library is axios (https://github.com/axios/axios), which you can install in your React app with npm:

npm install axios

You must add the following import command to your React component before using it:

import axios from 'axios';

The axios library has some benefits, such as automatic transformation for JSON data. The following code shows an example call being made with axios:

axios.get('http://someapi.com')
.then(response => console.log(response))
.catch(error => console.log(error));

The axios library has its own call methods for the different HTTP methods. For example, if you want to make a POST request and send an object in the body, axios provides the axios.post method:

axios.post('http://someapi.com', { newObject })
.then(response => console.log(response))
.catch(error => console.log(error));

Now, we are ready to look at practical...

Working on practical examples

In this chapter we will go through two examples of using some open REST APIs in your React app.

OpenWeatherMap API

First, we will make a React app that shows the current weather in London. This weather data will be fetched from OpenWeatherMap (https://openweathermap.org/). You need to register with OpenWeatherMap to get an API key. We will use a free account as that is sufficient for our needs. Once you have registered, navigate to your account information to find the API keys tab. There, you'll see the API key that you need for your React weather app:

Figure 8.1 – The OpenWeatherMap API key

Let's create a new React app with create-react-app:

  1. Open a terminal in Windows or Terminal in macOS/Linux, and type the following command:
    npx create-react-app weatherapp
  2. Navigate to the weatherApp folder:
    cd weatherapp
  3. Start your app with the following command:
    npm start
  4. Open your project folder with VS Code and open the App.js file in the editor view. Remove all the code inside the <div className="App"></div>...

Summary

In this chapter, we focused on networking with React. We started with promises, which make asynchronous network calls easier to implement. This is a cleaner way to handle calls, and it's much better than using traditional callback functions.

In this book, we are using the fetch API for networking. Therefore, we went through the basics of using fetch. We implemented two practical React apps using the fetch API to call REST APIs and we presented the response data in the browser.

In the next chapter, we will look at some useful React components that we are going to use in our frontend.

Questions

Answer the following questions to test your knowledge of this chapter:

  1. What is a promise?
  2. What is fetch?
  3. How should you call the REST API from the React app?
  4. How should you handle the response of the REST API call?

Further reading

Packt has other great resources available for learning about React. These are as follows:

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Full Stack Development with Spring Boot and React - Third Edition
Published in: Apr 2022Publisher: PacktISBN-13: 9781801816786
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Juha Hinkula

Juha Hinkula is a software development lecturer at Haaga-Helia University of Applied Sciences in Finland. He received an MSc degree in Computer Science from the University of Helsinki and he has over 17 years of industry experience in software development. Over the past few years, he has focused on modern full stack development. He is also a passionate mobile developer with Android-native technology, and also uses React Native.
Read more about Juha Hinkula