Fetch data is a basic requirement of practically every React application. There are a variety of ways to fetch data in React, including the built-in Fetch API, Axios, async/await syntax, and others. We’ll look at some of these methods in detail.
React components can simply fetch their data. There are several options where to fetch the data:
- Who is interested in this data? The data-fetching component should be the shared parent component for all of the components.
- Where exactly do you want to display a load indicator (e.g. load spinner, progress indicator) when data is expected from an asynchronous request? The load indicator can be mapped to the common parent component from the first criterion. Then the common parent component will still be the data-fetching component.
- When the loading indicator should be displayed in a higher-level component, the data fetching needs to be transferred to this component.
- When a load indicator needs to be displayed in the child components of the common parent component, not necessarily in those components that need the data, the common parent component becomes the component to fetch the data as well. The status of the load indicator can then be transferred to all the child components that are concerned with displaying the load indicator.
- Where is the optional error message you want to show if the request fails? The same rules from the second criterion for the load indicator apply here.
Is all about where the data should be fetched in the React component architecture. However, when data should be fetched and how should it be fetched once the generic parent component has been matched? Let’s look at some ways to retrieve data using React.
In most modern browsers, the Fetch API is a tool that is built into the window object (
window. fetch) and allows to make
Using a React Hooks
Axios is a client-side HTTP library based on promises. It facilitates sending asynchronous
HTTP requests to REST endpoints and helps perform CRUD operations. That REST API/endpoint is an external API like Google API or GitHub API, or it can be your backend Node.js server.
This article is about a React application, so we’ll use React hooks to access states and other functions. The hooks we’ll be using are
useState(). Essentially in this case it’ll be the
useEffect() hook to fetch posts after the app renders/mounts, while the
useState() hook will help create local storage for our data. First, you need to install axios by
npm install axios.
GETRequests with Axios in React.
GETrequests are used to retrieve data from an endpoint, and this happens right after the application is rendered due to the
useEffect()hook. First, it will be using a variable and then the
.get()method will be connected to make a
GETrequest to the endpoint/API. Then the
.then()callback is used to get all the response data, as there is already an Axios instance that stores the base URL assigned to the variable (client).
GETRequest. When the
GETrequest has been successfully implemented, the next step is to consume data stored in the post-state.
POSTRequest with Axios in React. The
POSTrequest is used to send data to an endpoint and works similarly to a
GETrequest, except with the function generated to perform this task, running when the form is otherwise or submitted. It will be using a
.post()method. The function accepts an object to send data to and adds data to the state, removing previous data and adding new data.
DELETErequest is used to delete certain data from both the endpoint/API and the user interface. It will be using a
Overall, Axios is about improving quality of life, not anything else. But making lots of small, step-by-step changes to the quality of life workflow can significantly improve the quality and speed of development.
ECMAScript 2017 introduced the ability to use promises using async / await syntax. The advantage of this is that it allows removing
.finally() callbacks and simply getting asynchronously resolved data back as if there was writing synchronous code with no promises at all. In other words, there is no need to rely on callbacks when using async / await in React. Remember when using
useEffect that the effect function cannot be made asynchronous.
useEffect hook with all its templates in each component you want to fetch data in is time-consuming eventually. For reducing code reuse, you can use a custom hook as a special abstraction, which you can write yourself from a third-party library (using the react-fetch-hook library). Running a custom hook on
HTTP requests allows for making the components more concise. The only thing you need to do is to call the hook at the top of the component.
The load and error state should thus be able to use the same structure for this component as before when all data is returned but without
useEffect. The code no longer needs to be used to resolve the promise from the
GET request every time the request has to be executed.
The React-Query library allows handling the data implied in web service requests and maintaining applications while improving user experience. First, you need to import React,
useQuery hook, and the
axios libraries. Next, define an asynchronous function. And create a functional React component.
The difference between React-Query and the common data fetching library
useEffect is that React-Query will return previously fetched data first and then re-fetch it again. Whereas
useEffect fetches the data independently of the changed data and reloads the page.
React is a great tool for building rich and high-scalable user interfaces. Some of its powerful features are the ability to fetch data and interact with it externally for a web application. There are many ways to consume the REST API in a React application, but in this guide, we’ve discussed how you can consume it using some of the most popular methods, such as Axios (a promise-based HTTP client),
useFetch hooks, React-Query Library, etc.