How to make GET API request in Reactjs


We have already learn about how to make API calls in HTML using jQuery and AJAX , if you do miss the article here is the quick link to the posts.

React

React is a JavaScript UI library for building super responsive web application. We can connect React with Nodejs-Express API/ any API (already covered the API creation with Node-Express in the past tutorials, following links will be helpful for revisiting those posts)

Create API with Node-Express

GET API call with Axios

Axios is a NPM package which let you use API in react. To use axios we have to install the package and make API request. The GET can be used to the fetch the data from the server.

A GET request is used to fetch data from the server, for example retrieve a set of products from the server based on user query

componentDidMount() {
   axios
    .get("http://localhost:3005/post/find")
    .then((response) => {
     
       if (response.data.length > 0) {
         this.setState({
           posts: response.data ,
        });
      }
    })
    .catch((error) => {
       console.log(error);
    });
}

In the above code we have make call to the API end point post/find which will pull out all the posts from the server. Since it is a collection we have checked for the array length to make sure the data retrieved. Also note that the best place to call API is componentDidiMount method which is a react lifecycle method.

componentDidiMount is one of the lifecycle method Reactjs had which automatically called before displaying components on the UI

Following react posts help you to build better React apps

Published by

Manoj

A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.