Reader small image

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

Product typeBook
Published inOct 2023
PublisherPackt
ISBN-139781805122463
Edition4th Edition
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

Consuming the REST API with React

This chapter explains networking with React. This is a really important skill that we need in most 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 OpenWeather and GitHub REST APIs to demonstrate how to consume RESTful web services with React. We will also see the React Query library in action.

In this chapter, we will cover the following topics:

  • Promises
  • Using the fetch API
  • Using the Axios library
  • Practical examples
  • Handling race conditions
  • Using the React Query library

Promises

The traditional way to handle an asynchronous operation is to use callback functions for the success or failure of the operation. If the operation succeeds, the success function is ­called; otherwise, the failure function is called. The following (abstract) 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);

Nowadays, promises are a fundamental part of asynchronous programming in JavaScript. 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. If you are using an older library for asynchronous operations that doesn’t support promises, the code becomes much more difficult...

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 or jQuery Ajax API, 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 and it is supported by modern browsers natively.

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 response, the syntax is as follows:

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

The fetch() method returns a promise that contains the response. You can use the json() method to extract the JSON data from a response, and this method also returns a promise.

The response that is...

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 statement to your React component before using it:

import axios from 'axios';

The axios library has some benefits, such as automatic transformation of the JSON data, so you don’t need the json() function when using axios. The following code shows an example call being made using 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...

Practical examples

In this section, we will go through two examples of using public REST APIs in your React apps. In the first example, we use the OpenWeather API to fetch the current weather for London and render it in the component. In the second example, we use the GitHub API and allow the user to fetch repositories by keyword.

OpenWeather API

First, we will make a React app that shows the current weather in London. We will show the temperature, description, and weather icon in our app. This weather data will be fetched from OpenWeather (https://openweathermap.org/).

You need to register with OpenWeather to get an API key. A free account will be 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 10.1: The OpenWeather API key

Your API key will be activated automatically, up to 2 hours after your successful...

Handling race conditions

If your component makes several requests quickly, it can lead to a race condition that can create unpredictable or incorrect results. Network requests are asynchronous; therefore, requests don’t necessarily finish in the same order as they were sent.

The following example code sends a network request when the props.carid value changes:

import { useEffect, useState } from 'react';
function CarData(props) {
  const [data, setData] = useState({});
  useEffect(() => {
    fetch(`https ://carapi .com/car/${props.carid}`)    .then(response => response.json())
    .then(cardata => setData(cardata))
  }, [props.carid]);
  
  if (data) {
    return <div>{data.car.brand}</div>;
  } else {
    return null;
  }
continue...

Now, if carid changes quickly multiple times, the data that is rendered might not be from the last request that was sent.

We can use the useEffect cleanup function to avoid race conditions. First...

Using the React Query library

In proper React apps where you make a lot of network calls, the use of third-party networking libraries is recommended. The two most popular libraries are React Query (https://tanstack.com/query), also known as Tanstack Query, and SWR (https://swr.vercel.app/). These libraries provide a lot of useful features, such as data caching and performance optimization.

In this section, we will learn how you can use React Query to fetch data in your React app. We will create a React app that fetches repositories from the GitHub REST API using the react keyword:

  1. First, create a React app called gitapi using Vite and select the React framework and JavaScript variant. Install dependencies and move to your project folder.
  2. Next, install React Query and axios using the following commands in your project folder (Note! In this book, we are using Tanstack Query v4):
    // install v4
    npm install @tanstack/react-query@4
    npm install axios
    
  3. ...

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 Axios and React Query libraries for networking in our frontend. We went through the basics of using these libraries. We implemented two React example apps using the fetch API and Axios to call REST APIs, and we presented the response data in the browser. We learned about race conditions and looked at how to fetch data using the React Query library.

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

Questions

  1. What is a promise?
  2. What are fetch and axios?
  3. What is React Query?
  4. What are the benefits of using a networking library?

Further reading

There are other good resources available for learning about promises and asynchronous operations. A couple are as follows:

Learn more on Discord

To join the Discord community for this book – where you can share feedback, ask the author questions, and learn about new releases – follow the QR code below:

https://packt.link/FullStackSpringBootReact4e

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Full Stack Development with Spring Boot 3 and React - Fourth Edition
Published in: Oct 2023Publisher: PacktISBN-13: 9781805122463
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 AU $19.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