How to AJAX API Calls in Reactjs
Posted By : Damini Sharma | 07-Sep-2020
React is a library, for building a user interface or UI, not a complete framework like Angular or AngularJS. In MVC architecture, React represents the View part. So if you have used the client-side framework before, you will notice the lack of many abstractions such as services to make HTTP calls (equivalent to $http in AngularJS).
So, If you want to ask what's the React equivalent for sending AJAX calls? There isn't!
You shouldn't consider as a weakness of the library because React isn't supposed to handle all the tasks usually handled by frameworks. The whole purpose of React is to render stateless components which are also known as dump components with no data and stateful components using data from props and state that's usually fetched from an API server.
How to Fetch Data from HTTP Server to React? So, how to fetch data from a remote HTTP server
Choosing the Right HTTP Call Mechanism:-
There are many libraries with different features, that can be used to fetch data from remote server.
1. You can use Axios to React if you feel comfortable working with JavaScript Promises.
2. If you like to work with cutting-edge standards in React, you can use the browser fetch API.
3. You can also use jQuery, but it's not recommended to include the whole library you can use just for the sake of making API calls.
4.You can use XMLHttpRequest interface.
5. Calling APIs using the Fetch API.
Let's see a practical example, using the browser's fetch API.
We can create a simple React app that would send API calls to the Reddit server to fetch some subreddit posts.
Creating a New React Project:-
So, we go ahead and create a new React project. I'm using and suggesting create-react-app because it saves you from the hassle of configuring WebPack and lets you quickly generate a starter project to build your app.
Installing create-react-app
If you follow this approach, you will able to use
Generating a New React Project
Now you can generate a new React project as follows:-
create-react-app react-ajax-demo
cd react-ajax-demo
How to Use the Fetch API?
The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as request and response. It also provides a global fetch() method that provides an easy way, logical way to fetch resources asynchronously across the network.
Now, let's fetch some data from Reddit. update the code to reflect these changes in src/App.js:-
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
posts: []
};
}
fetchFirst(url) {
var that = this;
if (url) {
fetch('https://www.reddit.com/r/' + url + '.json').then(function (response) {
return response.json();
}).then(function (result) {
//console.log(result.data.children);
that.setState({ posts: result.data.children, lastPostName: result.data.children[result.data.children.length - 1].data.name });
console.log(that.state.posts);
});
}
}
componentWillMount() {
this.fetchFirst("reactjs");
}
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">React AJAX Example</h1>
</header>
<p className="App-intro">
<ul>
{this.state.posts.map(post =>
<li key={post.id}>{post.title}</li>
)}
</ul>
</p>
</div>
);
}
}
export default App;
Right in the fetchFirst() method, we are sending a GET request to fetch data from 'https://www.reddit.com/r/' + url + '.json' using the following code:-
fetch('https://www.reddit.com/r/' + url + '.json').then(function (response) {
return response.json();
}).then(function (result) {
console.log(result.data.children);
});
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Damini Sharma
Damini is a young enthusiastic web designer who loves to explore latest, cutting edge tools and technologies in web development.