Reader small image

You're reading from  React and React Native - Fifth Edition

Product typeBook
Published inApr 2024
Reading LevelBeginner
PublisherPackt
ISBN-139781805127307
Edition5th Edition
Languages
Tools
Right arrow
Authors (2):
Mikhail Sakhniuk
Mikhail Sakhniuk
author image
Mikhail Sakhniuk

Mikhail Sakhniuk is Software Engineer with high proficiency in JavaScript, React and React Native. He has more than 5 years of experience in developing web and mobile applications. He has worked for startups, fintech companies, and product companies with more than 20 million users. Currently, Mikhail is working at Miro as a Frontend Engineer. In addition, he owns and maintains a few open-source projects. He also shares his experience and knowledge through books and articles.
Read more about Mikhail Sakhniuk

Adam Boduch
Adam Boduch
author image
Adam Boduch

Adam Boduch has been involved in large-scale JavaScript development for nearly 15 years. Before moving to the frontend, he worked on several large-scale cloud computing products using Python and Linux. No stranger to complexity, Adam has practical experience with real-world software systems and the scaling challenges they pose.
Read more about Adam Boduch

View More author details
Right arrow

Fetching Data from a Server

The evolution of web technologies has made the interaction of browsers with servers and the processing of server data an integral part of web development. Today, it’s challenging to draw a clear line between traditional web pages and full-fledged web applications. At the heart of this evolution is the ability of JavaScript in the browser to make requests to the server, efficiently process the received data, and dynamically display it on the page. This process has become the foundation for creating the interactive and responsive web applications we see today. In this chapter, we will explore various approaches and methods used to fetch data from the server, discuss their impact on the architecture of web applications, and acquaint ourselves with modern practices in this area.

So, in this chapter, we will cover the following topics:

  • Working with remote data
  • Using the Fetch API
  • Using Axios
  • Using TanStack Query
  • ...

Technical requirements

You can find the code files for this chapter on GitHub at https://github.com/PacktPublishing/React-and-React-Native-5E/tree/main/Chapter11.

Working with remote data

In the realm of web development, the journey of fetching data from servers has seen remarkable transformations. In the early 90s, the web’s infancy with HTTP 1.0 marked the beginning of server communication. Web pages were static, and HTTP requests were basic, fetching whole pages or static assets. Every request meant establishing a new connection, and interactivity was minimal, mostly limited to HTML forms. Security was also basic, reflecting the nascent state of the web.

The turn of the millennium witnessed a significant shift with the rise of Asynchronous JavaScript and XML (AJAX). This brought an era of enhanced interactivity, allowing web applications to communicate with the server in the background without reloading the whole page. It was powered by the XMLHttpRequest object. Here’s a simple example of using XMLHttpRequest to fetch data:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
  if (xhr.readyState ...

Using the Fetch API

Let’s explore how we can retrieve data from a server in practice. We’ll start with the Fetch API, the most common and fundamental approach provided by web browsers.

Before we begin, let’s create a small application that fetches user data from GitHub and displays their avatar and basic information on the screen. To do this, we’ll need an empty Vite project with React. You can create it with the following command:

npm create vite@latest

Since we’re using TypeScript in our examples, let’s start by defining the GitHubUser interface and all the necessary parameters.

To find out what data the server returns, we often need to refer to the documentation, usually provided by backend developers. In our case, since we’re using the GitHub REST API, we can find user information in the official GitHub documentation at this link: https://docs.github.com/en/rest/users/users?apiVersion=2022-11-28.

Let’...

Using Axios

In this section, we will explore one of the most popular libraries for working with the server, called Axios. This library is similar to the Fetch API but also provides additional features that make it a powerful tool for handling requests.

Let’s take our previous project and make some changes to it. First, let’s install Axios as a dependency:

npm install axios

One of Axios’s features is the ability to create instances with specific configurations, such as headers, base URLs, interceptors, and more. This allows us to have a preconfigured instance tailored to our needs, reducing code repetition and making it more scalable.

Let’s create an API class that encapsulates all the necessary logic for working with the server:

class API {
  private apiInstance: AxiosInstance;
  constructor() {
    this.apiInstance = axios.create({
      baseURL: "https://api.github.com",
    });
    this.apiInstance.interceptors.request...

Using TanStack Query

TanStack Query, more commonly known as React Query, is a library that has taken server interaction to a new level. This library allows us to request data and cache it. As a result, we can call the same useQuery hook a lot of times during one rendering, but only one request will be sent to the server. The library also includes built-in loading and error states, simplifying the handling of request states.

To get started, let’s install the library as a dependency for our project:

npm install @tanstack/react-query

Next, we need to configure the library by adding the QueryClientProvider:

const queryClient = new QueryClient();
ReactDOM.createRoot(document.getElementById("root")!).render(
  <QueryClientProvider client={queryClient}>
    <App />
  </QueryClientProvider>
);

After this setup, we can start working on the app. One of the unique features of this library is that it is agnostic to the tool you use for...

Using GraphQL

Earlier in this chapter, we discussed what GraphQL is and how it allows us to specify the exact data we want from the server, reducing the amount of transferred data and speeding up data fetching.

In this example, we will explore GraphQL in conjunction with the @apollo/client library, which provides similar functionality to React Query but works with GraphQL queries.

To begin, let’s install the necessary dependencies using the following command:

npm install @apollo/client graphql

Next, we need to add a provider to our application:

const client = new ApolloClient({
  uri: "https://api.github.com/graphql",
  cache: new InMemoryCache(),
  headers: {
    Authorization: 'Bearer YOUR_PAT', // Put your GitHub personal access token here
  },
});
ReactDOM.createRoot(document.getElementById("root")!).render(
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>
);

At this stage, during...

Summary

In this chapter, we explored how to fetch data from the server. We began by briefly reviewing the history of client-server communication and highlighting the primary methods of interacting with servers. Next, we built an application to retrieve GitHub user data using the Fetch API, Axios, TanStack Query, and Apollo GraphQL.

The techniques you learned in this chapter will enable you to significantly expand the capabilities of your own web applications. By efficiently fetching data from the server, you can create dynamic, data-driven experiences for your users. Whether you are building a social media app that displays real-time feeds, an e-commerce site with up-to-date product information, or a dashboard that visualizes live data, the skills you gained will prove invaluable.

In the next chapter, we will delve into managing the application state using state management libraries.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
React and React Native - Fifth Edition
Published in: Apr 2024Publisher: PacktISBN-13: 9781805127307
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

Authors (2)

author image
Mikhail Sakhniuk

Mikhail Sakhniuk is Software Engineer with high proficiency in JavaScript, React and React Native. He has more than 5 years of experience in developing web and mobile applications. He has worked for startups, fintech companies, and product companies with more than 20 million users. Currently, Mikhail is working at Miro as a Frontend Engineer. In addition, he owns and maintains a few open-source projects. He also shares his experience and knowledge through books and articles.
Read more about Mikhail Sakhniuk

author image
Adam Boduch

Adam Boduch has been involved in large-scale JavaScript development for nearly 15 years. Before moving to the frontend, he worked on several large-scale cloud computing products using Python and Linux. No stranger to complexity, Adam has practical experience with real-world software systems and the scaling challenges they pose.
Read more about Adam Boduch