While developing dynamic applications, we come across scenarios where we must fetch or store data in external sources. Modern web applications depend entirely upon fetching data from remote servers to display content dynamically, store user data, and perform various operations. Although React is a front-end library, it provides us with ways to make the client-side data fetching requests. The Fetch API is the most fundamental tool for doing so. In this article, we will explore how to fetch data from servers using the Fetch API.
Client-Side Data Fetching
Web applications often rely on the backend servers for the following reasons:
- Retrieving Dynamic Data: Data that needs to be updated dynamically, such as product listings, news feeds, and user profiles, requires fetching data from backend servers.
- User Authentication: The systems that require users to log in perform validation and authentication by checking the credentials stored on the servers.
- Submitting User Input: Data submitted by the user is sent to the servers for processing and storage.
- Performing Actions: The actions the user performs on a web app, such as placing an order, updating information, deleting an item, reporting someone, etc, are performed by sending requests to the servers to update data on the backend.
Hyper Text Transfer Protocol (HTTP)
The communication between the client and server uses HTTP, which is the foundation of data transfer on the web. In our scenario, React acts as a client sending requests to the server and displaying the response from the server.
The Fetch API: Our Built-in Data Courier
JavaScript provides a built-in and powerful way to make HTTP requests, i.e., the Fetch API. It is built directly into modern web browsers and provides a cleaner and flexible way to handle network requests. It also makes the asynchronous operations easier to manage.
Asynchronous Operations allow programs to execute operations independently without affecting or blocking the execution of other blocks.
Making Basic GET Requests: Asking For Information
The GET is the most common HTTP request. It is used to retrieve information from the database. In other words, it sends the retrieval requests to the servers. Let's see how to make GET requests using the Fetch API.
First, create a new project named Fetch.js. Now, add the following code to it:
import React, { useState, useEffect } from 'react';
function UsersData() {
const [users, userSetter] = useState([]);
const [loading, loader] = useState(true);
const [error, errorSetter] = useState(null);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/users') // A Dummy URL for API Endpoint
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json(); // This convers the response to JSON
})
.then(data => {
userSetter(data); // The Fetched Data Updates the Components State
loader(false);
})
.catch(error => {
errorSetter(error); // If any errors occur during fetching, they are handled here
loader(false);
});
}, []); // The Empty Array ensures that this runs only once.
if (loading) {
return <p>Loading users...</p>;
}
if (error) {
return <p>Error fetching users: {error.message}</p>;
}
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
export default UsersData;
In the above code, the useState()
hook is used to track the state of the component, and the useEffect()
hook performs the data fetching once the component has been rendered. The empty dependency array in useState([])
ensures that this effect runs only once.
Inside the useEffect()
hook, the fetch('https://jsonplaceholder.typicode.com/users')
serves as a dummy API endpoint. When working on a real project, we replace this with the actual API endpoint. You can also fetch data from localhost if you have a local server. It initiates the GET request.
The response from the server is handled by the .then()
method. First, we check if we have got a valid HTTP response using the response.ok
. If the operation is successful, it returns the HTTP code under 2xx. If not, we throw an error.
Afterwards, the response.JSON ()
method converts the response body into JSON format. The following .then()
method receives this JSON formatted data and updates the user and loading states.
The .catch()
block handles any error that occurs during data fetching or parsing. Again, it sets the error and loading states.
Finally, using the conditional rendering, we display the loading message if the data is loading, an error message if an error is caught, or the data if the request was successful.
Other HTTP Methods
Besides fetching data, you can perform various other operations using the Fetch API, such as sending new entries to the server (POST), updating an existing entry (PUT/PATCH), and deleting a resource from the server (DELETE). However, understanding only the GET HTTP request method would be enough at this level. You can learn the aforementioned methods as you advance in React.
Loading States: Keeping Users Informed
When you send or fetch data from the server, it sometimes takes more time than expected. Keeping the user engaged and informed about the status is a good practice in such situations. Therefore, we display the Loading indicator to display the Loading… message while the data is being fetched. This way, the user knows something is happening, and the data will display soon. This is an effective and widely used method of enhancing the user experience. Besides displaying the plain loading message, you can be creative and use the sliders, progress bars, and spinners to add more interactivity to your UIs.
To build dynamic and interactive web pages in React, the developers must be acquainted with the Fetch API, handle different HTTP requests, errors, and responses, and provide loading feedback to keep the users informed. In this article, we have covered the GET request, but you'll learn about the other methods as you advance in React. In the next article, we will learn how to navigate a single-page application (SPA) in React.