[React] Http

Setup

Fetch data with axiom

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import axios from 'axios';

componentDidMount() {
axios.get('/posts').then (// async request return a Promise
response => {
console.log(response);
const posts = response.data.slice(0, 4);
const updatedPosts = posts.map(post => { // Transform data: add a fake author property on each post object
return {
...post,
author: 'Max'
}
})
this.setState({
posts: updatedPosts
});
}
)
}

Fetch data on update

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
state = {
loadedPost: null,
}
componentDidUpdate() {
if (this.props.id) {
if (!this.state.loadedPost || this.state.loadedPost && this.state.loadedPost.id !== this.props.id) { // check state loadedPost to avoid infinite loop
axios.get('/posts/' + this.props.id).then(
(response) => {
console.log(response);
this.setState({loadedPost: response.data}); // will raise infinite loop since it will call componentDidUpdate() again and again

}
).catch(
error => {
console.log(error);
}
);
}
}
}
render () {
let post = <p style={{textAlign: 'center'}}>Please select a Post!</p>;
if (this.props.id) {
post = <p style={{textAlign: 'center'}}>Loading...</p>;
}
if (this.state.loadedPost) {
post = (
<div className="FullPost">
<h1>{this.state.loadedPost.title}</h1>
<p>{this.state.loadedPost.body}</p>
<div className="Edit">
<button className="Delete">Delete</button>
</div>
</div>

);
}
return post;
}

Post data

1
2
3
4
5
6
7
8
9
10
11
12
postDataHandler() {
const post = {
title: this.state.title,
body: this.state.content,
author: this.state.author,
}
axios.post('https://jsonplaceholder.typicode.com/posts', post).then(
(response) => {
console.log(response);
}
);
}

Delete data

1
2
3
4
5
6
7
deletePostHandler = () => {
axios.delete('https://jsonplaceholder.typicode.com/posts/' + this.props.id).then(
(response) => {
console.log(response);
}
);
}

Setting up Interceptors to execute code globally

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import axios from 'axios';

axios.defaults.baseUrl = 'https://jsonplaceholder.typicode.com';
axios.defaults.headers.post['Content-Type'] = 'application/json';

axios.interceptors.request.use(request=>{
return request; // Keep request going
}, error => {
console.log(error);
return Promise.reject(error);
});

axios.interceptors.response.use(response=>{
return response; // Keep request going
}, error => {
console.log(error);
return Promise.reject(error);
});

// To remove interceptors
axios.interceptors.request.eject(myInterceptor);

Axios Instance

1
2
3
4
5
6
7
8
9
10
// Create an axios.js
import axios from 'axios';

const instance = axios.create({
baseURL: 'https://...'
});

instance.defaults.headers.common['Authorization'] = 'AUTH TOKEN FROM'

export default instance;