<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Tech Bytes</title>
    <description>The latest articles on DEV Community by Tech Bytes (@techbytes).</description>
    <link>https://dev.to/techbytes</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F645104%2Fb79e4017-3e1d-41d3-8507-68d02ad4099a.png</url>
      <title>DEV Community: Tech Bytes</title>
      <link>https://dev.to/techbytes</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/techbytes"/>
    <language>en</language>
    <item>
      <title>A beginners guide to using Axios with Reactjs</title>
      <dc:creator>Tech Bytes</dc:creator>
      <pubDate>Tue, 15 Nov 2022 12:41:35 +0000</pubDate>
      <link>https://dev.to/techbytes/a-beginners-guide-to-using-axios-with-reactjs-358l</link>
      <guid>https://dev.to/techbytes/a-beginners-guide-to-using-axios-with-reactjs-358l</guid>
      <description>&lt;p&gt;In this article, we are going to learn how to use Axios for GET, POST, PUT and other HTTP requests in React.js application. I will use MongoDB, Node, and Express.js to create a backend server for the React app.&lt;/p&gt;

&lt;p&gt;In the React environment we have plenty of options for pretty much everything. For the network also we have plenty of options like fetch ,axios , react-http-client , etc.&lt;/p&gt;

&lt;p&gt;Among others, the Axios provides plenty of features like global-config , Interceptors , better error handlers, etc.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is Axios?
&lt;/h2&gt;

&lt;p&gt;Axios is a popular, promise-based HTTP client that sports an easy-to-use API and can be used in both the browser and Node.js. We can use Axios with React to make requests to an API, return data from the API, and then do things with that data in our React app.&lt;/p&gt;

&lt;p&gt;With Axios, A developer can also take advantage of async/await for more readable asynchronous code.&lt;/p&gt;

&lt;p&gt;Here we will use JSON placeholder API for fetching the list of dummy users.&lt;/p&gt;

&lt;h3&gt;
  
  
  Install Axios
&lt;/h3&gt;

&lt;p&gt;At first, we need to install Axios into the react project. Run below command to install it in the project.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;// install with npm&lt;br&gt;
npm install axios — save&lt;/code&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  GET Request with Axios
&lt;/h3&gt;

&lt;p&gt;Create a new component named UserList and hook it into the componentDidMount lifecycle and fetch data with Get request after importing axios&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';
import axios from 'axios';
export default class UserList extends React.Component {
state = {
persons: []
}
componentDidMount() {
axios.get(`https://jsonplaceholder.typicode.com/users`)
.then(res =&amp;gt; {
const users = res.data;
this.setState({ users });
})
}
render() {
return (
&amp;lt;ul&amp;gt;
{ this.state.users.map(user =&amp;gt; &amp;lt;li&amp;gt;{user.name}&amp;lt;/li&amp;gt;)}
&amp;lt;/ul&amp;gt;
)
}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code, At the top React &amp;amp; Axios library is imported. axios.get(URL) is used to get a promise which returns a response object. The received data in res.data is assigned to users. Information like status code and others can also be received with the response.&lt;/p&gt;

&lt;h3&gt;
  
  
  POST Request with Axios
&lt;/h3&gt;

&lt;p&gt;As we know that Axios also handle another HTTP request such as POST, PUT, etc. So create another component named AddUser for showing an example of POST request which will add a user and put below code inside it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from ‘react’;
import axios from ‘axios’;

export default class AddUser extends React.Component {
 state = {
 name: ‘’,
 }

 handleChange = event =&amp;gt; {
 this.setState({ name: event.target.value });
 }

 handleSubmit = event =&amp;gt; {
 event.preventDefault();

 const user = {
 name: this.state.name
 };

 axios.post(`https://jsonplaceholder.typicode.com/users`, { user })
 .then(res =&amp;gt; {
 console.log(res);
 console.log(res.data);
 })
 }

 render() {
 return (
 &amp;lt;div&amp;gt;
 &amp;lt;form onSubmit={this.handleSubmit}&amp;gt;
 &amp;lt;label&amp;gt;
 Person Name:
 &amp;lt;input type=”text” name=”name” onChange={this.handleChange} /&amp;gt;
 &amp;lt;/label&amp;gt;
 &amp;lt;button type=”submit”&amp;gt;Add&amp;lt;/button&amp;gt;
 &amp;lt;/form&amp;gt;
 &amp;lt;/div&amp;gt;
 )
 }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above code mainly makes an HTTP POST request to the server and add the data to the database.&lt;/p&gt;

&lt;h3&gt;
  
  
  DELETE Request with Axios
&lt;/h3&gt;

&lt;p&gt;axios.delete is used to make Delete request to the server, URL need to pass into it as a parameter.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;handleSubmit = event =&amp;gt; {
 event.preventDefault();

 axios.delete(`https://jsonplaceholder.typicode.com/users/${this.state.id}`)
 .then(res =&amp;gt; {
 console.log(res);
 console.log(res.data);
 })
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Error handling
&lt;/h3&gt;

&lt;p&gt;In the real world, every application uses some common rule like “If the response header contains 401 then redirects to the login page, etc”. For that, we need to handle the application level.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import Axios from "axios";
import utils from "./utils";



Axios.interceptors.response.use(undefined, function (error) {
    // Error Status code
    const statusCode = error.response ? error.response.status : null;

    // We show the console error only in the development mode.
    if(process.env.NODE_ENV === 'development'){
        console.log('error', error);
        console.log('errorType', typeof error);
        console.log('error', Object.assign({}, error));
        console.log('getOwnPropertyNames', Object.getOwnPropertyNames(error));
        console.log('stackProperty', Object.getOwnPropertyDescriptor(error, 'stack'));
        console.log('messageProperty', Object.getOwnPropertyDescriptor(error, 'message'));
        console.log('stackEnumerable', error.propertyIsEnumerable('stack'));
        console.log('messageEnumerable', error.propertyIsEnumerable('message'));
    }
    // If the un-auth error, we should redirect to login page.
    if(statusCode === 401){
        utils.redirectTo("/login");
    }
    // for the both development &amp;amp; production, we need to show the alert.
    utils.error("An Error in the server");

    // return promise object
    return Promise.reject(error);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above code is the simplest usage of Axios-interceptors for the global error handler but in the real world, an application needs to handle a lot in both production and development modes.&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
