Calling backend from React

From Logic Wiki
Jump to: navigation, search


Instal Axios

npm i axios

Usage

import axios from 'axios';

...
async componentDidMount(){
  const promise = axios.get('http://somedomain.com/products');
  const response = await promise;
} 

Simpler

 async componentDidMount(){
  const response = await axios.get('http://somedomain.com/products');
} 

Even More Simpler

state = { 
   posts:[]
};

 async componentDidMount(){
  const { data: posts } = await axios.get('http://somedomain.com/products');
  this.setState({ posts });
} 

Adding Data

const obj = { title:'a', body:'b' };
const {data:post} = await axios.post('http://somedomain.com/products', obj);

const posts = [post, ...this.state.posts];
this.setState({ posts });

Updating Data

handleUpdate = post => {
post.title = "UPDATED";
 await axios.put('http://somedomain.com/products/' + post.id, post);
 await axios.patch('http://somedomain.com/products/' + post.id, {title:post.title );

const posts = [ ...this.state.posts];
const index = posts.indexOf(post);
posts[index] = {...post};
this.setState({ posts });

put updates the object patch updates only one property of the object

Deleting Data

handleDelete = async post => {
  await axios.delete('http://somedomain.com/products/' + post.id);
 const posts = this.state.posts.filter(p=> p.id !== post.id);
 this.setState({ posts });

};


Interceptor

axios.interceptors.response.use(success, error)
axios.interceptors.response.use(null, error => {
  console.log('INTERCEPTOR CALLED');
  return Promise.reject(error);
});

Placing token into the custom header

axios.defaults.headers.common['x-http-token'] = token