React Axios Example | How To Use React With Axios

In this demo project, I will show you how to create React Axios Example. How to use React with Axios from scratch. This article covers integrating Axios with React, the proper lifecycle hook to make requests, the most common request types, and how properly handle errors.

For this example, I will use Node.js, Express.js, and MongoDB as backend platforms, and database. On the frontend, I will use React.js and Bootstrap. In every project, we need to create a REST API at some stage. Axios is a lightweight HTTP client based similar to a Fetch API.

Axios is a promise-based async/await library for the readable asynchronous code. We can easily integrate with React.js, and it is effortless to use in any frontend framework.

React Axios Example

If you are new to React; you will also learn about the basic concepts such as:

The state object is used to contain the pieces of state of the app.

The setState() method to change the values in the state object.

The componentDidMount() life-cycle hook. This is executed when your React component inserted/mounted in the DOM.

JSX for adding HTML in JavaScript.

We start this example by installing the React.js using create-react-app.

What is Axios

Axios is a popular HTTP client that allows us to make GET and POST requests from the browser.

Therefore, 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.

Databases and web services have something called an API (Application Programming Interface), which apps can use to communicate with through the URL.

In other words, an API allows apps to retrieve or send the data to and from the databases or web services.

Apps use HTTP requests, for example, GET, POST, and PUT, to communicate with APIs. In short, Axios makes it easy for our apps to perform these commands.

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

Step 2: Install Bootstrap 4.

Install Bootstrap 4 using the following command.

npm install bootstrap --save

Include bootstrap.min.css file inside 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;

Okay, now we have successfully integrated Bootstrap 4.

Step 3: Create React components.

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

Okay, inside components folder, create two components.

Create.js 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 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();

Now, 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.

Step 5: Create a Navigation bar.

Okay, now 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.

So, now we have two fields.

server name 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 that will send the POST request to the node.js server.

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

Finally, when we click the submit button, then 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 in Node.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. 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. 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.

Okay, we will install Axios via npm using the following command.

npm install axios --save

Now, send the post request along with the form data to the node and express server.

First, we need to 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. Open your browser console panel and see the response.

We can that values are saved in the MongoDB database.

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 that data in a React app.

Add a componentDidMount() method inside the Index.js, and 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> ); } }

Okay, now write the stateless component, and that is TableRow.js component, which we need to create inside 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 the 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 try/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

Steps to use Github Code

Start the MongoDB server using this command: mongod Clone The Repository. Go into the project folder. Install all the dependencies using this command: npm install Start the Node.js server using this command: nodemon server Start the react.js development server using this command: yarn start Go to this URL: http://localhost:3000/create

Conclusion

Handling requests to React with Axios is straightforward to understand.

So, in this React Axios demo, I have described the following things.

What is Axios, and how to install and configure it? Install React.js and configure React with Axios. Configure Node.js, Express, and MongoDB backend and database. Send an Axios Post request from React frontend. Send an Axios Get request to fetch the data from the server.

Finally, React Axios Example is over. Thanks for taking it.

People Also Ask

React Redux Node MongoDB JWT Authentication

React Redux Axios Example

How To Connect React and Redux

React CRUD Example

Redux Thunk Example