In this post, we are going to explain how to send HTTP requests from React. We can send requests from every component but we are going to do that by centralizing the HTTP logic as some kind of a repository. For this type and size of the project, the centralized solution fits perfectly fine.

But if you have a larger and more complicated project it would be a good practice to split repository files, and thus, splitting the states. We are going to use axios as a third party library to send HTTP requests and Redux for centralizing the repository logic.

There is one important thing to note. We don’t have to use Redux to create a central place for handling HTTP requests (this is just one way), we could create an additional file and export functions (that are going to handle HTTP requests) from that file. But Redux is quite common in the React projects, therefore we are going to explain in detail how Redux works.

So let’s start.

If you want to see all the basic instructions and complete navigation for the .NET Core series, check out the following link: Introduction to the .NET Core series.

For the complete navigation and all the basic instructions of the React series, check out: Introduction to the React series.

For the previous part check out: Navigation and Routing

The source code is available at GitHub: React series – react-series-part3-end branch

This post is divided into several sections:

Creating the Axios Instance

To install axios execute this command:

Axios install - HTTP, Axios, Redux

Even though we could use native axios instance (the one we have just installed) to send HTTP requests, the better way is to create our own instance. In this custom instance, we can define base url property and assign headers and other useful elements. If we need more instances of axios we can create them as well. So let’s create our custom axios instance.

Inside the src folder, create a new folder and name it axios. Inside that folder create a new file and name it axios.js. Now let’s modify the axios.js file:

In this code example, we import the axios library and then create a new instance with the additional properties. This is very useful because we don’t have to write full endpoints anymore (axios.get(http://locahost:5000/api/owner)) for our HTTP requests. Now we can use relative paths (axios.get(/api/owner)) because we are using our custom axios instance with the predefined baseURL property.

About Redux

Redux is a state container for the JavaScript applications. Even though it seems a bit complicated at the beginning, with a bit of practice, you are going to realize that Redux is not that hard at all. And it helps a lot. Redux is not React’s library, it can fit with any other JavaScript framework, but it works well with React.

To install Redux execute this command:

Redux installation - HTTP, Axios, Redux

The Redux on its own is not going to be enough. We need to create a relation between React and Redux and to accomplish that let’s install the react-redux library:

React-Redux installation - HTTP, Axios, Redux

Excellent.

Now we have both libraries required for our application to work with Redux. So, we can continue to the Redux implementation. But before we continue, let’s take a look at this diagram which closely explains how Redux works (Components part is a starting point):

Redux diagram - HTTP, Axios, Redux

Redux – Action Types

Let’s start by creating the following structure inside the src folder:

Redux folder structure

In the actions folder, let’s create a new file and name it actionTypes.js. Now let’s modify that file:

Our reducer file (which we are going to create later in this post) is going to use this action types to switch between different ways of updating the state.

Redux – Repository Actions (Action Container)

We need to create a new file in the actions folder and name it repositoryActions.js. We are going to handle HTTP async requests inside this file and return an object which reducer file is going to use to update the state. Every returned object must have at least one property with a name “type”. The value of the type property is going to be one of the actionTypes from the actionType.js file (previously created).

Now let’s add the import statements for the actionTypes and for our axios instance in the repositoryActions.js file:

Then we need to add two functions. One to handle the GET request and the second one to return an object with the type property and the data from the server:

What are we doing in here?

We are exporting thegetData function. This function will be called from our component to fetch the data from the server (therefore we must export it from this file). Then with axios, we are sending the GET request. If it is successful we are dispatching the getDataSuccess function which returns an object for the reducer file to use. This object has the mandatory type property and also the data property fetched from the server.

Below the getData function, let’s implement all the other functions, by following the same pattern:

That’s it, we now have an implementation of the actions.js file and it’s a time to create and implement the reducer file.

React – Reducer

Let’s create a new file inside the reducers folder and name it repositoryReducer.js:

Reducer file - HTTP, Axios, Redux

In this file, we are going to check the type property which we return from the repositoryAction.js file. Then, based on the value of the type property, we are going to update our state.

So, let’s modify the repositoryAction.js file:

We import the actionTypes and create the state with the name initialState. The data property is going to store the data from the server and the showSuccessModal property serves to show or hide the success modal when a POST, PUT or DELETE action is successful.

Now let’s create a reducer function below our state object:

This reducer function is accepting two parameters, the state which we initialize with our initial state and the action. We are going to use this state parameter to update our initialState and the action parameter to store the object (with at least type property) sent from therepositoryAction.js file. So, whenever we dispatch any action (which returns an object with at least type property and all the other properties) from the repositoryAction.js file, this reducer function is going to trigger and to accept the sent object inside the action parameter. As a consequence, the reducer is going to switch through the action types and to execute the corresponding function.

Finally, let’s add those corresponding functions right above our reducer function:

These functions are updating our state. First, we are deeply cloning our state object by using the spread (…) operator and then just overriding the property we want to update in our state object. Because objects and arrays are reference types we need to execute a deep clone on them prior to any changes. That way we are updating the state immutably.

For this state to be available inside any owner component we need to register this reducer to the index.js file.

Reducer File Registration

Before we register our reducer file we must install one more third-party library named thunk:

Thunk installation

This library enables us to send async requests with the Redux actions.

Now we can register our reducer:

In the code above, we import all the necessary files we need to register our reducer. Then we create the store and apply the middleware thunk and finally use the Provider component to provide our reducer to the React app.

There it is, we have prepared our redux setup for our project. The best part about it is that we can use it for any component inside our project and if we have components which require more complex or different kind of redux setup, all we have to do is to create another action and reducer file and to register it inside the index.js file. In one of the next posts, we are going to show you how to accomplish that by combining reducers inside theindex.js file.

Conclusion

Even though you may find a little bit hard to understand how Redux works, we believe that with this article and some practice you’ll get a handle on it. Bottom line is that Redux is not that hard, just as the opposite, it is pretty straightforward, after some practice.

By reading this post, you’ve learned:

  • The way to set up the new Axios instance
  • How to install Redux and React-Redux
  • About Action Types, Action Containers and Reducers
  • How to register reducer file

Thank you for reading the article and I hope you found something useful in it.

In the next part of the series, we are going to learn how to prepare HTTP repository by using Axios and Redux.


If you have enjoyed reading this article, please leave a comment in the comments section below, and if you want to receive the notifications about the freshly published content we encourage you to subscribe to our blog.