Reactjs HTTP request
In this article, we will learn how to react works with HTTP and an introduction to how HTTP request are generally handled in a Reactjs application.
When you are building a web application, you more often than not have to reach out to the server to fetch some data or send some data based on user interaction. This web application in our context is of course a react application. The react is a library for building user interfaces, it is in no way concerned about HTTP.
This is a very important interview question: how do we make Ajax requests in React or how do we make API calls in React? You can easily answer that question, first, let me tell you that React itself does not have a particular way to fetch or send data to the server. In fact, as far as React is concerned it doesn’t even have to know that there is a server in the above picture. Remember React components simply read props and state and render the UI, therefore to use some data from the server you just have to get the data into your component’s props or state.
Now if React isn’t going to handle the requests, who will be doing that? This is where you will have to make use of an HTTP library. There are a few popular ones out there but I prefer Axios. The fetch API is also good consideration as it is more standardized but for our understanding, we will stick to Axiox. Our focus is not really on the library, we use it rather how we use it with React.
Install Axios in React
To add the Axios package to our application, we must run the below command after creating our React App.
npm install axios
When the command completes Axiox should be added to the list of dependencies. So, we can now start making HTTP requests from our application.