visit
npm install axios
yarn add axios
import React from 'react';
import axios from 'axios';
class YourComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: []
}
}
componentDidMount() {
// Your axios request here
}
render() {
return (
// Your jsx goes here
);
}
}
axios({ method: 'http request method', url: 'Api url' });
GET Requests
With this basic pattern in mind, an Axios GET request would be as follows:const apiUrl = '//your-api.com/';
axios({ method: 'get', url: `${apiUrl}` });
axios({ method: 'get', url: `${apiUrl}` })
.then(response => {
this.setState({
posts: response.data
})
});
POST Requests
In the case of a typical POST request, data is passed along with the API request. This data usually can reside either in the component's state or a redux store. Usually, the data that the user wishes to post to the database is obtained from a form. We would update the component's state with the handleChange function. Our Axios request would be made in the handleSubmit function. When the form is submitted, a POST request is sent to the API. This can be done as follows:class YourComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
post: ''
}
}
handleChange(e) {
const { value } = e.target;
this.setState({
post: value
});
}
handleSubmit(e) {
e.preventDefault();
const { post } = this.state;
axios({
method: 'post',
url: `${apiUrl}/posts`,
data: post
})
}
render() {
return (
// Your form resides here
);
}
}
DELETE Requests
DELETE requests are similar to POST requests. They are made upon interaction with a button in the view. In this case, a handleClick function can be employed to make the request when a 'delete' button is clicked. This can be done as follows:class YourComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: [
{
id: 1,
content: 'The first post'
}
]
}
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) {
e.preventDefault();
const { id } = e.target;
const apiUrl = '//your-api.com/';
axios({
method: 'delete',
url: `${apiUrl}/posts/${id}`
})
}
render() {
const { posts } = this.state;
return (
<div>
{posts.map(post => (
<div key={post.id}>
<p>{post.content}</p>
<div>
<input
type="button"
id={post.id}
value="Delete"
onClick={this.handleClick}
/>
</div>
</div>
))}
</div>
);
}
}
Requests with JWT
JWT (JSON Web Tokens) can be used to authenticate users in web-based applications. These tokens are usually generated by sending a POST request to a properly configured API. Once the token is generated, they are stored for use via localStorage. In such a case, the token would need to form part of the HTTP request made. To illustrate this, we'll revisit the GET request example:const apiUrl = '//your-api.com/';
const token = `Bearer ${localStorage.getItem('jwt')}`;
axios({
method: 'get',
url: `${apiUrl}`,
headers: { Authorization: token }
});