React fetch data guide
Tags: javascript, react, api, webdev
Published: 2022-08-11 12:00:00

Fetch data is a basic requirement of practically every  [React](https://flatlogic.com/blog/crud-app/) 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](https://flatlogic.com/blog/using-react-with-express/).

In most modern browsers, the Fetch API is a tool that is built into the window object (`window. fetch`) and allows to make  `HTTP`  requests very simply by using the  [JavaScript](https://flatlogic.com/blog/7-trends-in-javascript-to-look-for-in-2020/)  promises.

## Using a React Hooks

### Axios

Axios is a client-side HTTP  [library](https://flatlogic.com/blog/best-libraries-for-react-i18n/)  based on promises. It facilitates sending asynchronous  `HTTP`  requests to REST endpoints and helps perform  [CRUD](https://flatlogic.com/blog/react-pagination-guide-and-best-react-pagination-libraries/)  operations. That REST API/endpoint is an external API like Google API, GitHub API, or it can be your backend  [Node.js](https://flatlogic.com/blog/top-javascript-calendar-plugins/)  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  `useEffect()`  and  `useState()`. Essentially in this case it’ll be the  `useEffect()`  hook to fetch posts after the  [app](https://flatlogic.com/blog/difference-between-react-and-angular-a-comparison-guide-for-2021/)  renders/mounts, while the  `useState()`  hook will help create local storage for our data. First, you need to install axios by  [npm](https://flatlogic.com/blog/what-is-npm/).

-   **Making  `GET`  Requests with Axios in React.** `GET`  requests 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  `GET`  request 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).

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b7de6hbgsw8x6ycgs8x6.png)


-   **Consuming**  **`GET`  Request.** When the  `GET`  request has been successfully implemented, the next step is to consume data stored in the post-state.
-   **Making  `POST`  Request with Axios in React.** The  `POST`  request is used to send data to an endpoint and works similarly to a  `GET`request, 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.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f5q3or2f2shsydhufivx.png)
  
-   **Making  `DELETE`  Request.** `DELETE`  request is used to delete certain data from both the endpoint/API and the  [user interface](https://flatlogic.com/blog/7-reasons-why-ui-matters-in-web-development/). It will be using a  `.delete()`  method.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wgmjb3nasjva1g2j2swc.png)

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.

### `async/await`  syntax

ECMAScript 2017 introduced the ability to use promises using async / await syntax. The advantage of this is that it allows removing  `.then()`,  `.catch()`  and  `.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.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d3c7eci2tuhjf5bzrs72.png)


### useFetch

Writing the  `useEffect`  hook with all its  [templates](https://flatlogic.com/blog/top-19-remarkable-javascript-table-libraries-and-plugins/)  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.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kvirotnc4zr27eheesqu.png)

### React-Query

The React-Query library allows handling the data implied in  [web](https://flatlogic.com/blog/top-angular-open-source-projects/)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.

## Conclusion

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](https://flatlogic.com/blog/web-application-templates-with-perfect-design/). There are many ways to consume the REST API in a React application, but in this  [guide](https://flatlogic.com/blog/react-table-guide-and-best-react-table-examples/), we’ve discussed how you can consume it using some of the most popular methods, such as Axios (a promise-based HTTP client),  `useEffect`  and  `useFetch`  hooks, React-Query Library, etc.