In this video we are going to learn about Using Axios.
Axios is a lightweight HTTP client based on the XMLHttpRequests service.
It is similar to the Fetch API and is used to perform HTTP requests.
Lest see how can we use axios in react.
For that first of all install the axios.
So switch to the command promt and here run the command.
Allright now axios has been installed.
Now run the react application again.
So just type here.
Now switch to the project and here just create a new component.
Let say component name is Blog.js.
Now inside the Blog component lets create the class as following.
Now go to the App.js file and here import the Blog component.
Now use add Blog inside the Switch
Now save and lets check.
So switch to browser and go to the url /blog.
You can see here the posts.
So in this way you can use axios in react.
Axios is a lightweight HTTP client based on the XMLHttpRequests service.
It is similar to the Fetch API and is used to perform HTTP requests.
Lest see how can we use axios in react.
For that first of all install the axios.
So switch to the command promt and here run the command.
npm install axios
Allright now axios has been installed.
Now run the react application again.
So just type here.
npm start
Now switch to the project and here just create a new component.
Let say component name is Blog.js.
Now inside the Blog component lets create the class as following.
import React, { Component } from 'react';
import axios from 'axios';
class Blog extends Component {
state = {
posts:[]
}
componentDidMount(){
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(res=>{
this.setState({
posts:res.data.slice(0,10)
});
});
}
render() {
const {posts} = this.state;
const postList = posts.length?(
posts.map(post=>{
return(
<div key={post.id}>
<h4>{post.title}</h4>
<p>{post.body}</p>
</div>
)
})
):(<div>No post yet</div>);
return (
<div>
<h3>Blog Posts</h3>
{postList}
</div>
)
}
}
export default Blog;
Now go to the App.js file and here import the Blog component.
import Blog from './components/Blog';
Now use add Blog inside the Switch
<BrowserRouter>
<Switch>
<Route exact path='/blog' component={Blog}/>
</Switch>
</BrowserRouter>
Now save and lets check.
So switch to browser and go to the url /blog.
You can see here the posts.
So in this way you can use axios in react.