DEV Community

Mohit
Mohit

Posted on • Originally published at Medium

Different Methods for Data Fetching in React

React is really awesome when it comes to displaying data in a component view, I will discuss all the best approaches.

You can visit the Gitlab link fir accessing the example used below:

https://gitlab.com/mohit199thd/react-data-patterns-demo

How To Fetch Data In React

If you are a beginner who’s familiar with building simple React Projects then you may have worked on simple methods of data fetching where you don't work on bigger and higher amounts of data to be fetched. In your React journey as you go along your apps will get more complex and data fetching with the right techniques becomes a requirement. There are plenty of ways to fetch data in React using the built-in Fetch API, Axios, async/await, and much more

  1. Server-Provided Data

This approach is straightforward and works pretty well in most cases where the data is embedded in the HTML sent from the server. And if we need fresh data you need to refresh the page manually or have the page refresh periodically.

For Example:

This method is not that relevant to React application, but we can call this method a more dynamic way to get data from the server to the browser.
Still, a lot of Web Apps use this & in case JavaScript is disabled or when we have to deal with old browsers it is even the best way to fetch data.

How React Components Fetch Data

There are several approaches for data fetching in React Components.

  1. Start with no data, and then fetch data on user-based action (clicking on a button).
  2. Loading data at once.
  3. Loading data periodically

As the component is totally autonomous and no other component can tell that it's the time to load some data, so will load the data for the first time in the componentDidMount() and set a timer that will fetch the data again every 7 seconds.
Our UserTableAutonomus component below is a standard React class component,

The state includes two fields:

Alt Text

Boolean isFetching initialized to false since it is not fetching yet.

An empty list of users, which is the data it needs to fetch.
The render() method renders the BootstrapTable component passing the current user from the state. The actual data fetching happens in the componentDidMount() which is a React lifecycle method, there are two reasons why we are not using componnetWillMount() as first its deprecated as of React 17 & when we use the Fetch API or Axios componentWillMount(), the render will happen without waiting for it to finish, and this will cause and empty render for the first time.

Alt Text

The componentDidMount() is called after the first render so we still need to handle the first empty render, in this case, we use the ‘Fetching Data’ message, you can also choose your own initial data fetching in the constructor.
So now we will fetch our data in componentDidMount() and the code simply calls the fetchUsers() method and starts a timer to call fetchUsers() every 7 seconds.

Alt Text

componentWillMount() method is called when our component goes away and clearInterval() will stop the time interval by setting it to null.
The fetchUsers() set the isFetching state variable to True, so as soon as new data gets fetched the ‘Fetching Data’ message gets renders by the component. And then after getting some data it set isFetching back to False.

Alt Text

  1. The Fetch API

I have used the Fetch API in the function fetchUsersWithFetchAPI() and assigned variable fetchUsers so the component just calls fetchUsers().

It starts by setting the isFetching variable to true, then it calls fetch which returns a promise which further resolves to a response, then the response json() method returns a JavaScript object.
Then it resets isFetching to false and in case something goes wrong the catch handlers log the errors to the console and reset the isFetching variable when the Fetching process is finished.

Alt Text

  1. Using Axios

We will use Axios in the UserTableRenderProps component. Axios also has a promise-based API similar to Fetch, but it saves the JSON parsing phase and handles all the errors. Where the Fetch API returns an error 404 as a normal response, so you might need to check the response on your code and throw an error yourself. Axios have almost similar code to Fetch API but with one less step and more error handling.

Alt Text

Fetch vs Axios

We can communicate with the server through HTTP protocol using both, but which is better for you will depend on your project goals.

Fetch API provides a fetch() method on the window project, as well as a JavaScript interface for accessing HTTP request and responses, fetch has only one mandatory argument that the URL of a resource to be fetched, it returns a promise that can be used to retrieve the response of the request
Whereas Axios is a JavaScript library that enables to make an HTTP request from Node.js or XML & supports the Promise API in the ES6 version of JavaScript.

Read the full post at:

https://medium.com/javascript-in-plain-english/data-fetching-in-react-668ef136efd9

Top comments (0)