How to Use Axios With React: The Definitive Guide (2023)

Here are the steps to use Axios with React.

Step 1: Install React.js

Install create-react-app globally using the following command. You need to enter this command in admin mode.

npm install -g create-react-app 

create-react-app reactaxios

React Axios Tutorial Example From Scratch

Step 2: Install Bootstrap 4.

Install Bootstrap 4 using the following command.

npm install bootstrap --save

Include the bootstrap.min.css file inside the App.js file.

// App.js

import React, { Component } from 'react';

import '../node_modules/bootstrap/dist/css/bootstrap.min.css';

class App extends Component {
  render() {
    return (
      <div class="container">
        React Axios Tutorial
      </div>
    );
  }
}

export default App;

We have successfully integrated Bootstrap 4.

Step 3: Create React components.

Inside the src folder, create a new folder called components. Inside the components folder, create two components.

  1. Create.js
  2. Index.js
// Create.js

import React, { Component } from 'react';

export default class Create extends Component {
    render() {
        return (
            <div>
                <p>Welcome to Create Component!!</p>
            </div>
        )
    }
}
// Index.js

import React, { Component } from 'react';

export default class Index extends Component {
    render() {
        return (
            <div>
                <p>Welcome to Index Component!!</p>
            </div>
        )
    }
}

Step 4: Create Routing of the components.

Install the following routing library.

npm install react-router-dom --save

Go to the index.js file and Wrap the BrowserRouter object around the App.js component.

// App.js

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(
    <BrowserRouter>
    <App />
    </BrowserRouter>, document.getElementById('root'));
registerServiceWorker();

Define the routes for each component.

// App.js

import React, { Component } from 'react';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
import Create from './components/Create';
import Index from './components/Index';

import '../node_modules/bootstrap/dist/css/bootstrap.min.css';

class App extends Component {
  render() {
    return (
      <Router>
        <div className="container">
          <h2>Welcome to React Express Tutorial</h2>
          <ul>
            <li><Link to={'/create'}>Create</Link></li>
            <li><Link to={'/index'}>List</Link></li>
          </ul>
          <hr />
          <Switch>
              <Route exact path='/create' component={ Create } />
              <Route path='/index' component={ Index } />
          </Switch>
        </div>
      </Router>
    );
  }
}

export default App;

Now, go to this URL: http://localhost:3000/create.

Axios React Example

 

Step 5: Create a Navigation bar.

Write the following code inside the App.js file.

// App.js

import React, { Component } from 'react';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
import Create from './components/Create';
import Index from './components/Index';

import '../node_modules/bootstrap/dist/css/bootstrap.min.css';

class App extends Component {
  render() { 
    return (
      <Router>
        <div className="container">
          <nav className="navbar navbar-expand-lg navbar-light bg-light">
            <a className="navbar-brand">React Express App</a>
            <div className="collapse navbar-collapse" id="navbarSupportedContent">
              <ul className="navbar-nav mr-auto">
                <li className="nav-item"><Link to={'/create'} className="nav-link">Create</Link></li>
                <li className="nav-item"><Link to={'/index'} className="nav-link">List</Link></li>
              </ul>
              <hr />
            </div>
          </nav> <br />
          <Switch>
              <Route exact path='/create' component={ Create } />
              <Route path='/index' component={ Index } />
          </Switch>
        </div>
      </Router>
    );
  }
}

export default App;

Step 6: Create a Bootstrap 4 Form.

Add the HTML Form code inside Create.js.

// Create.js

import React, { Component } from 'react';

export default class Create extends Component {
    render() {
        return (
            <div style={{marginTop: 50}}>
                <h3>Add New Server</h3>
                <form>
                    <div className="form-group">
                        <label>Add Host Name:  </label>
                        <input type="text" className="form-control"/>
                    </div>
                    <div className="form-group">
                        <label>Add Server Port: </label>
                        <input type="text" className="form-control"/>
                    </div>
                    <div className="form-group">
                        <input type="submit" value="Add Node server" className="btn btn-primary"/>
                    </div>
                </form>
            </div>
        )
    }
}

Step 7: Submit The Create.js Form.

We have two fields.

  1. server name
  2. server port

So we need to create two functions that can track both the values and set the state according to it. Also, create the third function to send the POST request to the node.js server.

Now, I need to create an event that tracks the state of both input types.

Finally, when we click the submit button, data is provided to the server.

// Create.js

import React, { Component } from 'react';

export default class Create extends Component {

    constructor(props) {
        super(props);
        this.onChangeHostName = this.onChangeHostName.bind(this);
        this.onChangePort = this.onChangePort.bind(this);
        this.onSubmit = this.onSubmit.bind(this);

        this.state = {
            name: '',
            port: ''
        }
    }
    onChangeHostName(e) {
        this.setState({
            name: e.target.value
        });
    }
    onChangePort(e) {
        this.setState({
            port: e.target.value
        });
    }
    onSubmit(e) {
        e.preventDefault();
        console.log(`name is ${this.state.name} and port is ${this.state.port}`);
        this.setState({
            name: '',
            port: ''
        })
    }

    render() {
        return (
            <div style={{marginTop: 50}}>
                <h3>Add New Server</h3>
                <form onSubmit={this.onSubmit}>
                    <div className="form-group">
                        <label>Add Host Name:  </label>
                        <input type="text" className="form-control" value={this.state.name}  onChange={this.onChangeHostName}/>
                    </div>
                    <div className="form-group">
                        <label>Add Server Port: </label>
                        <input type="text" className="form-control" value={this.state.port}  onChange={this.onChangePort}/>
                    </div>
                    <div className="form-group">
                        <input type="submit" value="Add Node server" className="btn btn-primary"/>
                    </div>
                </form>
            </div>
        )
    }
}

Step 8: Create a backend server inNode.js

First, start the MongoDB database server using the following command.

mongod

In the root folder, create one file called server.js.

Now, install the following node.js dependencies.

npm install express nodemon body-parser cors mongoose --save

Also, we need to install nodemon as a development dependency.

npm install nodemon --save-dev

Okay, now write the following code inside a server.js file.

// server.js

const express = require('express');
const app = express();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const PORT = 4000;
const cors = require('cors');

app.use(cors());
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

app.listen(PORT, function(){
  console.log('Server is running on Port: ',PORT);
});

Now, create a DB.js file inside the root folder.

// DB.js

module.exports = {
    DB: 'mongodb://localhost:27017/axios'
}

Now, import this DB.js file into the server.js file and connect a node.js application to the MongoDB database.

// server.js

const express = require('express');
const app = express();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const PORT = 4000;
const cors = require('cors');
const config = require('./DB');

mongoose.connect(config.DB).then(
    () => {console.log('Database is connected') },
    err => { console.log('Can not connect to the database' +err)
});

app.use(cors());
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

app.listen(PORT, function(){
  console.log('Server is running on Port: ',PORT);
});

Now open the terminal, and you can see that our database is connected with our Node Express application.

Step 9: Create a Mongoose schema.

Create one folder inside root called models and inside that, create one file called ServerPort.js.

// ServerPort.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Define collection and schema for ServerPort
const ServerPort = new Schema({
  name: {
    type: String
  },
  port: {
      type: Number
  }
},{
    collection: 'servers'
});

module.exports = mongoose.model('ServerPort', ServerPort);

Step 10: Create Express Routes.

Create one folder called routes. Then, inside that routes folder, create one file called ServerPortRouter.js.

// ServerPortRouter.js

const express = require('express');
const app = express();
const ServerPortRouter = express.Router();

const ServerPort = require('../models/ServerPort');

ServerPortRouter.route('/add').post(function (req, res) {
  const serverport = new ServerPort(req.body);
  serverport.save()
    .then(serverport => {
        res.json('Server added successfully');
    })
    .catch(err => {
    res.status(400).send("unable to save to database");
    });
});

ServerPortRouter.route('/').get(function (req, res) {
    ServerPort.find(function (err, serverports){
    if(err){
      console.log(err);
    }
    else {
      res.json(serverports);
    }
  });
});

module.exports = ServerPortRouter;

Here, I have defined both GET and POST request routes.

I have used Mongoose ORM to save the data in the MongoDB database.

The final step is to import the ServerPortRouter.js file inside the server.js file. Thus, the server.js file looks like below.

// server.js

const express = require('express');
const app = express();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');

const PORT = 4000;
const cors = require('cors');
const config = require('./DB');
const ServerPortRouter = require('./routes/ServerPortRouter');

mongoose.connect(config.DB).then(
    () => {console.log('Database is connected') },
    err => { console.log('Can not connect to the database' +err)
});

app.use(cors());
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

app.use('/serverport', ServerPortRouter);

app.listen(PORT, function(){
  console.log('Server is running on Port: ',PORT);
});

Step 11: Install the Axios Library.

We will install Axios via npm using the following command.

npm install axios --save

Send the post request and form data to the node and express server.

First, we must import the axios library inside Create.js and use that library to send a POST request.

// Create.js

import React, { Component } from 'react';
import axios from 'axios';

export default class Create extends Component {

    constructor(props) {
        super(props);
        this.onChangeHostName = this.onChangeHostName.bind(this);
        this.onChangePort = this.onChangePort.bind(this);
        this.onSubmit = this.onSubmit.bind(this);

        this.state = {
            name: '',
            port: ''
        }
    }
    onChangeHostName(e) {
        this.setState({
            name: e.target.value
        });
    }
    onChangePort(e) {
        this.setState({
            port: e.target.value
        });
    }
    onSubmit(e) {
        e.preventDefault();
        const serverport = {
            name: this.state.name,
            port: this.state.port
        }
        axios.post('http://localhost:4000/serverport/add', serverport)
        .then(res => console.log(res.data));
        
        this.setState({
            name: '',
            port: ''
        });
    }

    render() {
        return (
            <div style={{marginTop: 50}}>
                <h3>Add New Server</h3>
                <form>
                    <div className="form-group">
                        <label>Add Host Name:  </label>
                        <input type="text" className="form-control"/>
                    </div>
                    <div className="form-group">
                        <label>Add Server Port: </label>
                        <input type="text" className="form-control"/>
                    </div>
                    <div className="form-group">
                        <input type="submit" value="Add Node server" className="btn btn-primary"/>
                    </div>
                </form>
            </div>
        )
    }
}

Now, enter the values and submit the form. Next, open your browser console panel and see the response.

React js Axios POST example

We can see that values are saved in the MongoDB database.

MERN Stack Example

Step 12: Send Axios GET request.

The most common type of HTTP request is the GET request. It allows us to retrieve data from an API and use it in a React app.

Add a componentDidMount() method inside the Index.js, then add the following code.

// Index.js

import React, { Component } from 'react';
import axios from 'axios';
import TableRow from './TableRow';

export default class Index extends Component {

  constructor(props) {
      super(props);
      this.state = {serverports: []};
    }
    componentDidMount(){
      axios.get('http://localhost:4200/serverport')
      .then(response => {
        this.setState({ serverports: response.data });
      })
      .catch(function (error) {
        console.log(error);
      })
    }
    tabRow(){
        return this.state.serverports.map(function(object, i){
            return <TableRow obj={object} key={i} />;
        });
    }

    render() {
      return (
        <div className="container">
            <table className="table table-striped">
              <thead>
                <tr>
                  <td>ID</td>
                  <td>Name</td>
                  <td>Port</td>
                </tr>
              </thead>
              <tbody>
                {this.tabRow()}
              </tbody>
            </table>
        </div>
      );
    }
  }

Now write the stateless TableRow.js component, which we must create inside the components folder.

// TableRow.js

import React, { Component } from 'react';

class TableRow extends Component {
  render() {
    return (
        <tr>
          <td>
            {this.props.obj._id}
          </td>
          <td>
            {this.props.obj.name}
          </td>
          <td>
            {this.props.obj.port}
          </td>
        </tr>
    );
  }
}

export default TableRow;

Okay, now go to http://localhost:3000/index.

We can see that we have successfully sent an Axios GET request from the React.js component.

So, in this example, we have seen React with Axios Get and React with Axios post requests.

Handling Errors in Axios with Async/Await

The usual way of handling errors in JavaScript when using promises is via the .catch() method. The beauty of using async/await is that we can forget about that and use tries/catch statements instead.

Here’s how the request above would be rewritten using try/catch. The request is also adjusted so that it will fail.

try {
  
  // Load async data from an inexistent endpoint.
  let serverData = await axios.get('http://localhost:4200/serverport');
} catch (e) {
  console.log(`Axios request failed: ${e}`);
}

And, of course, we get the error logged in our console.

The catch block is the perfect place to parse the returned error. It’s also a great place to show your users an appropriate feedback message.

Github Code

That’s it.

10 thoughts on “How to Use Axios With React: The Definitive Guide (2023)”

  1. This is my first time pay a visit at here and i am truly pleassant
    to read all at alone place.

    Reply
  2. Thank you very much for this tutorial Krunal, I followed your instruction but I could not see the data on the mongo db on my Robo 3t, where can I see your repo so I can compare my code to your and see where I am doing the erros. Also I did not see axios db on the tutorial , just DB. Thank you very much

    Reply
  3. Hi, first of all very thanks for the article, it is a good article for Full stack knowledge.

    I recently tried your exercise but I apparently get the error when I try to do Post request for /add. I always hit the network error issue and my data never gets post. I tried several ways but I could not get a proper solutions Just trying to figure out if I missed anything on the backend.

    It would be nice if you can shed some light on the issue. Below is the code i added in the createJS file for error handling and this is the place i always get network error.

    .catch(err => {
    console.log(err);
    });

    Reply
    • Hi Sorry but the issue is now fixed as I had forgot to start backenhttps://appdividend.com/2018/05/30/react-axios-tutorial-example-from-scratch/?bs-comment-added=1#respondd server.

      Reply

Leave a Comment

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