التخطي إلى المحتوى الرئيسي

Consume Rest API using AXIOS library in React-JS


AXIOS is another approach to consume rest API in react-js, it provides async and awaits () to call multiple rest API simultaneous.

It also provides promise-based API communication from the client machine to the server machine.no need to convert response data to JSON, it will automatically return JSON type data.

AXIOS library support on all web browsers and older versions also because it has no in-built API tools on browser.

It takes more process time as compared to the Fetch method but it provides better security as compare to Fetch. It has CSRF features to protect cross-site URL protection.

FEATURES OF AXIOS

    • Request and response interception
    • Streamlined error handling
    • Protection against XSRF
    • Support for upload progress
    • Response timeout
    • The ability to cancel requests
    • Support for older browsers
    • Automatic JSON data transformation

How to use it

1)  install axios library in React-JS

  npm install axios

Syntax pattern to use it

axios.get(apiUrl).then((repos) => {

      const allRepos = repos.data;

      setAppState({ loading: false, repos: allRepos });

    });

axios.all([
  axios.get('https://api.github.com/users/hacktivist123'),
  axios.get('https://api.github.com/users/adenekan41')
])
.then(response => {
  console.log('Date created: ', response[0].data.created_at);
  console.log('Date created: ', response[1].data.created_at);
});

// Make a GET request with a shorthand method
axios.get('https://api.github.com/users/hacktivist123');

// Make a Post Request with a shorthand method
axios.post('/signup', {
    firstName: 'shedrack',
    lastName: 'akintayo'
});

Now i am providing the example to use GET method 


import React from "react";
import axios from 'axios'
export class RestAPIExample extends React.Component
{
   constructor()
   {
    super();

    this.state = {

       tdata:[]      

     }
   }
  

   componentDidMount()
   {
    axios.get('https://shivaconceptsolution.com/webservices/showreg.php').then((repos=> {
    
      this.setState({ tdata: repos.data["result"] })

      console.log(this.state.tdata)
    });

    }

   render()

   {

       return(

           <div>
               <table border='1'>

               <tbody>
                  <tr><th>Username</th><th>EmailID</th><th>Password</th></tr>
                  {this.state.tdata.map((person,i)=> <TableRow Key={i} data={person} />)}   
                  </tbody>
               </table>
               <h1>Welcome in REST API Implementation in React JS</h1>
           </div>
       )
   }
}


class TableRow extends React.Component
{
    render()
    {
        return(

            <tr>

             <td>{this.props.data.UserName}</td>

             <td>{this.props.data.emailid}</td>

             <td>{this.props.data.password}</td>

             

          </tr>
        )
    }
}

Another Example is to call Rest API using AXIOS Library:-


import React from "react";
import axios from 'axios'
export class AxiosExample extends React.Component
{
   constructor()
   {
    super();

    this.state = {

       tdata:[]      

     }
   }
 

   componentDidMount()
   {
    axios.get('https://shivaconceptdigital.com/api/viewallcourse.php').then((repos) => {
   
      this.setState({ tdata: repos.data["result"]})

     // console.log(this.state.tdata)
    });

    }

   render()

   {

       return(

           <div>
               <table border='1'>

               <tbody>
                  <tr><th>Course ID </th><th>Course Name</th><th>Path</th><th>Fees</th></tr>
                  {this.state.tdata.map((person,i)=> <TableRow Key={i} data={person} />)}  
                  </tbody>
               </table>
               <h1>Welcome in REST API Implementation in React JS</h1>
           </div>
       )
   }
}


class TableRow extends React.Component
{
    render()
    {
        return(

            <tr>

             <td>{this.props.data.courseid}</td>

             <td>{this.props.data.coursename}</td>

             <td><img src={'https://www.shivaconceptdigital.com/images/'+this.props.data.path} width="50" height="50" /></td>

             <td>{this.props.data.fees}</td>
             

          </tr>
        )
    }
}


For more examples click here:-

Click to more example

Differences between Axios and Fetch:

AxiosFetch
Axios has url in request object.Fetch has no url in request object.
Axios is a stand-alone third party package that can be easily installed.Fetch is built into most modern browsers; no installation is required as such.
Axios enjoys built-in XSRF protection.Fetch does not.
Axios uses the data property.Fetch uses the body property.
Axios’ data contains the object.Fetch’s body has to be stringified.
Axios request is ok when status is 200 and statusText is ‘OK’.Fetch request is ok when response object contains the ok property.
Axios performs automatic transforms of JSON data.Fetch is a two-step process when handling JSON data- first, to make the actual request; second, to call the .json() method on the response.
Axios allows cancelling request and request timeout.Fetch does not.
Axios has the ability to intercept HTTP requests.Fetch, by default, doesn’t provide a way to intercept requests.
Axios has built-in support for download progress.Fetch does not support upload progress.
Axios has wide browser support.Fetch only supports Chrome 42+, Firefox 39+, Edge 14+, and Safari 10.1+ (This is known as Backward Compatibilty).

تعليقات

  1. I read your post. It is very informative and helpful to me. I admire the message valuable information you provided in your article.
    online training

    ردحذف

إرسال تعليق

POST Answer of Questions and ASK to Doubt

المشاركات الشائعة من هذه المدونة

Uncontrolled form input in React-JS

  Uncontrolled form input in React-JS? If we want to take input from users without any separate event handling then we can uncontrolled the data binding technique. The uncontrolled input is similar to the traditional HTML form inputs. The DOM itself handles the form data. Here, the HTML elements maintain their own state that will be updated when the input value changes. To write an uncontrolled component, you need to use a ref to get form values from the DOM. In other words, there is no need to write an event handler for every state update. You can use a ref to access the input field value of the form from the DOM. Example of Uncontrolled Form Input:- import React from "react" ; export class Info extends React . Component {     constructor ( props )     {         super ( props );         this . fun = this . fun . bind ( this ); //event method binding         this . input = React . createRef ();...

JSP Page design using Internal CSS

  JSP is used to design the user interface of an application, CSS is used to provide set of properties. Jsp provide proper page template to create user interface of dynamic web application. We can write CSS using three different ways 1)  inline CSS:-   we will write CSS tag under HTML elements <div style="width:200px; height:100px; background-color:green;"></div> 2)  Internal CSS:-  we will write CSS under <style> block. <style type="text/css"> #abc { width:200px;  height:100px;  background-color:green; } </style> <div id="abc"></div> 3) External CSS:-  we will write CSS to create a separate file and link it into HTML Web pages. create a separate file and named it style.css #abc { width:200px;  height:100px;  background-color:green; } go into Jsp page and link style.css <link href="style.css"  type="text/css" rel="stylesheet"   /> <div id="abc"> </div> Exam...

JDBC using JSP and Servlet

JDBC means Java Database Connectivity ,It is intermediates from Application to database. JDBC has different type of divers and provides to communicate from database server. JDBC contain four different type of approach to communicate with Database Type 1:- JDBC-ODBC Driver Type2:- JDBC Vendor specific Type3 :- JDBC Network Specific Type4:- JDBC Client-Server based Driver  or JAVA thin driver:- Mostly we prefer Type 4 type of Driver to communicate with database server. Step for JDBC:- 1  Create Database using MYSQL ,ORACLE ,MS-SQL or any other database 2   Create Table using database server 3   Create Form according to database table 4  Submit Form and get form data into servlet 5  write JDBC Code:-     5.1)   import package    import java.sql.*     5.2)  Add JDBC Driver according to database ide tools     5.3)  call driver in program         ...