Axios in react js

The Axios In React Js

Hi there guys in today’s tutorial we will be looking at Axios in React Js. Axios is a package that can be installed in React Js in different ways depending on the os.

So what is Axios? Axios is a promised-based HTTP client for JavaScript. It has the ability to make HTTP requests from the browser and handle the transformation of request and response data.

You can make the following HTTP requests as

GET /posts
GET /posts/1
GET /posts/1/comments
GET /comments?postId=1
POST /posts
PUT /posts/1
PATCH /posts/1
DELETE /posts/1

Let’s do an example

Steps:

Step 1:

Install react and axios

1. npx create-react-app demo-app
2. cd my-app
3. npm start

Install axios

Using npm:

$ npm install axios

Step 2:

Performing Get request

Make a folder and rename it as components using the following command…

mkdir src/components

In the components folder make the following file and update it with the following code.

a) src/components/Post.js

import axios from "axios";
import React from "react";

export default class Posts extends React.Component {
state = {
posts: []
}

componentDidMount() {
axios.get(`https://jsonplaceholder.typicode.com/posts`)
.then(res => {
const posts = res.data;
this.setState({ posts });
})
.catch(function (error) {
if (error.response) {
// Request made and server responded
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
});
}

render() {
return (
<ul>
{
this.state.posts
.map(post =>
<li key={post.id}>{post.title}</li>
)
}
</ul>
)
}
}

Locate the App.js file and update it with the code below…

update app.js with import Posts from ‘./components/Posts.js’;

and in the return section with Posts…

src/App.js


import React from 'react';
import Posts from './components/Posts.js';

function App() {
// eslint-disable-next-line no-lone-blocks
{
return (
<div className="App">
<Posts/>
</div>
)
}
}

export default App
run npm start

Step 3:

Performing Post request

a) src/components/Addpost.js

Update it with the code below…

Addpost.js

import React from 'react';
import axios from 'axios';

export default class Addpost extends React.Component {
state = {
title: ''
}

handleChange = event => {
this.setState({ title: event.target.value });
}

handleSubmit = event => {
event.preventDefault();

const post = {
title: this.state.title
};

axios.post(`https://jsonplaceholder.typicode.com/posts`, { post })
.then(res => {
console.log(res);
console.log(res.data);
})
}

render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<label>
Post title:
<input type="text" name="name" onChange={this.handleChange} />
</label>
<button type="submit">Add</button>
</form>
</div>
)
}
}

update the app.js (import Addpost from ‘./components/Addpost’;)

and in the return section with Addpost…

src/app.js

import React from 'react';
import Posts from './components/Posts.js';
import Addpost from './components/Addpost';

function App() {
// eslint-disable-next-line no-lone-blocks
{
return (
<div className="App">
<Posts/>
<Addpost/>
</div>
)
}
}

export default App
run npm start

Step 4:

Performing Delete request

Make a Deletepost.js and update it with the following code…

src/Deletepost.js

import React from 'react';
import axios from 'axios';

export default class Deletepost extends React.Component {
state = {
id: ''
}

handleChange = event => {
this.setState({ id: event.target.value });
}

handleSubmit = event => {
event.preventDefault();

axios.delete(`https://jsonplaceholder.typicode.com/posts/${this.state.id}`)
.then(res => {
console.log(res);
console.log(res.data);
})
}

render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<label>
Post ID:
<input type="number" name="id" onChange={this.handleChange} />
</label>
<button type="submit">Delete</button>
</form>
</div>
)
}
}

update the app.js with import Deletepost from ‘./Deletepost’;

and in the return section with Deletepost…

src/app.js

import React from 'react';
import Posts from './components/Posts.js';
import Addpost from './components/Addpost';
import Deletepost from './Deletepost';

function App() {
// eslint-disable-next-line no-lone-blocks
{
return (
<div className="App">
<Posts/>
<Addpost/>
<Deletepost/>
</div>
)
}
}

export default App
run npm start

Using a Base Instance in Axios

Base Instance refers to creating a single URL in one of your React Js files and from that file you can call the API to perform any HTTP requests. Let’s see it in action…

Step 1:

a) Create a new file in src/api.js and update it with the following code…

src/Api.js

import axios from 'axios';

export default axios.create({
baseURL: `http://jsonplaceholder.typicode.com/`
});

Update the src/components/Post.js with the below code…

src/components/Post.js

import React from "react";

import API from '../api';

export default class Posts extends React.Component {
state = {
posts: []
}

componentDidMount() {
API.get(`posts`)
.then(res => {
const posts = res.data;
this.setState({ posts });
})
.catch(function (error) {
if (error.response) {
// Request made and server responded
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
});
}

render() {
return (
<ul>
{
this.state.posts
.map(post =>
<li key={post.id}>{post.title}</li>
)
}
</ul>
)
}
}

and so forth for the rest…

Using async and await

The Async keyword is placed before a function. What it does it makes a function to return a promise.

Let’s do some changes in Post.js…

Post.js

import React from "react";

import API from '../api';

export default class Posts extends React.Component {
state = {
posts: []
}

async componentDidMount() {
const response = await API.get(`posts`);
const posts = response.data;
this.setState({ posts });

console.log(response);
console.log(response.data);

}

render() {
return (
<ul>
{
this.state.posts
.map(post =>
<li key={post.id}>{post.title}</li>
)
}
</ul>
)
}
}

Remember you can add the try-catch statement and console any errors.

Example…

async componentDidMount() {
try {
const response = await API.get(`posts`);
const posts = response.data;
this.setState({ posts });

console.log(response);
console.log(response.data);
}
catch(error) {
// handle error
console.log(error);
}
}

 

close

Sign up for free tutorials in your inbox.

We don’t spam! Read our privacy policy for more info.

Leave a Comment

Your email address will not be published.