Reader small image

You're reading from  React Application Architecture for Production

Product typeBook
Published inJan 2023
Reading LevelExpert
PublisherPackt
ISBN-139781801070539
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Alan Alickovic
Alan Alickovic
author image
Alan Alickovic

Alan Alickovic is a software developer, mentor and open source enthusiast from Serbia. He has extensive experience in building scalable applications from startups to large organizations. Besides being an individual contributor he has also been leading teams and mentoring other developers. By the time of this writing, he is working as a senior software engineer at Vroom.
Read more about Alan Alickovic

Right arrow

Integrating the API into the Application

In the previous chapter, we went through setting up the mocked API, which we will be consuming in our application.

In this chapter, we will be learning how to consume the API via the application.

When we say API, we mean the API backend server. We will learn how to fetch data from both the client and the server. For the HTTP client, we will be using Axios, and for handling fetched data, we will be using the React Query library, which allows us to handle API requests and responses in our React application.

In this chapter, we will cover the following topics:

  • Configuring the API client
  • Configuring React Query
  • Creating the API layer for the features
  • Using the API layer in the application

By the end of this chapter, we will know how to make our application communicate with the API in a clean and organized way.

Technical requirements

Before we get started, we need to set up our project. To be able to develop our project, we will need the following things installed on our computer:

  • Node.js version 16 or above and npm version 8 or above

There are multiple ways to install Node.js and npm. Here is a great article that goes into more detail: https://www.nodejsdesignpatterns.com/blog/5-ways-to-install-node-js.

  • VSCode (optional) is currently the most popular editor/IDE for JavaScript/TypeScript, so we will be using it. It is open source, has great integration with TypeScript, and we can extend its features via extensions. It can be downloaded from https://code.visualstudio.com/.

The code files for this chapter can be found here: https://github.com/PacktPublishing/React-Application-Architecture-for-Production

The repository can be cloned locally with the following command:

git clone https://github.com/PacktPublishing/React-Application-Architecture-for-Production...

Configuring the API client

For the API client of our application, we will be using Axios, a very popular library for handling HTTP requests. It is supported in both the browser and the server and has an API for creating instances, intercepting requests and responses, canceling requests, and so on.

Let’s start by creating an instance of Axios, which will include some common things we want to be done on every request.

Create the src/lib/api-client.ts file and add the following:

import Axios from 'axios';
import { API_URL } from '@/config/constants';
export const apiClient = Axios.create({
  baseURL: API_URL,
  headers: {
    'Content-Type': 'application/json',
  },
});
apiClient.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    const message =
   ...

Configuring React Query

React Query is a great library for handling async data and making it available in React components.

Why React Query?

The main reason that React Query is a great option for handling the async remote state is the number of things it handles for us.

Imagine the following component, which loads some data from the API and displays it:

const loadData = () => Promise.resolve('data');
const DataComponent = () => {
  const [data, setData] = useState();
  const [error, setError] = useState();
  const [isLoading, setIsLoading] = useState();
  useEffect(() => {
    setIsLoading(true);
    loadData()
      .then((data) => {
        setData(data);
      })
      .catch((error) => {
        ...

Defining the API layer for the features

The API layer will be defined in the api folder of every feature. An API request can be either a query or a mutation. A query describes requests that only fetch data. A mutation describes an API call that mutates data on the server.

For every API request, we will have a file that includes and exports an API request definition function and a hook for consuming the request inside React. For the request definition functions, we will be using the API client we just created with Axios, and for the hooks, we will be using the hooks from React Query.

We’ll learn how to implement it in action in the following sections.

Jobs

For the jobs feature, we have three API calls:

  • GET /jobs
  • GET /jobs/:jobId
  • POST /jobs

Get jobs

Let’s start with the API call that fetches jobs. To define it in our application, let’s create the src/features/jobs/api/get-jobs.ts file and add the following:

import { useQuery...

Consuming the API in the application

To be able to build the UI without the API functionality, we used test data on our pages. Now, we want to replace it with the real queries and mutations that we just made for communicating with the API.

Public organization

We need to replace a couple of things now.

Let’s open src/pages/organizations/[organizationId]/index.tsx and remove the following:

import {
  getJobs,
  getOrganization,
} from '@/testing/test-data';

Now, we must load the data from the API. We can do that by importing getJobs and getOrganization from corresponding features. Let’s add the following:

import { JobsList, Job, getJobs } from '@/features/jobs';
import {
  getOrganization,
  OrganizationInfo,
} from '@/features/organizations';

The new API functions are a bit different, so we need to replace the following code:

const [organization, jobs] = await Promise.all([
&...

Summary

In this chapter, we learned how to make the application communicate with its API. First, we defined an API client that allows us to unify the API requests. Then, we introduced React Query, a library for handling asynchronous states. Using it reduces boilerplate and simplifies the code base significantly.

Finally, we declared the API requests, and then we integrated them into the application.

In the next chapter, we will learn how to create an authentication system for our application where only authenticated users will be able to visit the dashboard.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
React Application Architecture for Production
Published in: Jan 2023Publisher: PacktISBN-13: 9781801070539
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
Alan Alickovic

Alan Alickovic is a software developer, mentor and open source enthusiast from Serbia. He has extensive experience in building scalable applications from startups to large organizations. Besides being an individual contributor he has also been leading teams and mentoring other developers. By the time of this writing, he is working as a senior software engineer at Vroom.
Read more about Alan Alickovic