Calling back-end Services React
(Part -1 )
JSON PlaceHolder
https://jsonplaceholder.typicode.com
it give us API ; which give us few end point.Using these endpoint we can send few http request to CRUD operation.
HTTP client
Front End =======> Back End (HTTP Request)to get or save data.? How can we do that
React care about rendering the View and managing the DOM.
It make sure what we have in Browser DOM is sync with state of your application !
React Doesn’t have a opinion about how to send http request to Server.(Angular HTTPmodule).
Use your preferred libr.
Fetch API
JqUERY ajax
Axios Getting Data
Right place to call a server and get some data is in componentDidMount lifecycle Hook.
componentDidMount(){
const promise = axios.get("https://jsonplaceholder.typicode.com/posts");
}What is promise above ?
It is a object that holds the result of asynchronous operation.
async operation is something that will finish in future.
First its in pending state ->resolved (Success) OR rejected (failure)
Server send header,request,status.
we can get the value using await keyword.Note : we should attach the function with async .
async componentDidMount(){
const response = await axios.get("https://jsonplaceholder.typicode.com/posts");console.log(response);}
Creating Data
async and . post() will be a key player.
handleAdd = async() => {
// console.log("Add");const obj = { title : 'a' , body : 'b'};const {data : post} = await axios.post(ApiEndPoint , obj);// console.log(post);const posts = [post,...this.state.posts];this.setState({posts});};
LifeCycle of Request
Every http request has the property called method that intent the property of request .
Common method
get (for getting data)
post (for creating data)
put (for updating data)
delete (for deleting data)
options Updating the data
axios.patch vs axios.put
we use patch to update one or more property and put to update all property.
axios.put(ApiEndPoint + '/' + post.id ,post);axios.patch(ApiEndPoint + '/' + post.id ,{ title : post.title});You can see we are only sending the properties that needs to be updated !
Deleting the data
axios.delete(ApiEndPoint + '/' + post.id)It is done with the help of axios.delete.
Optimistic vs Pessimistic Updates
Pessimistic Updates
handleDelete = async post => {await axios.delete(ApiEndPoint + '/' + post.id);
//Calling the server firstconst posts = this.state.posts.filter( p => p.id !== post.id);this.setState({posts});
//then updating the postconsole.log("Delete", post);};With this implementation if there occur an error while calling a server ; the reset of the function will not occur.
we are not sure call to the server will fail or success.
Optimistic
we assume most of the time call to the server will success.
So we will update the UI before server call and if it fails we will revert it back.
Steps :
- keep a storage of original content
- make the changes on the UI
- wait for the server to respond === “Success” ? “Bingo” : load the original content
Note : wrap the code in try catch method
const originalPost = this.state.posts;const posts = this.state.posts.filter( p => p.id !== post.id);this.setState({posts});try{await axios.delete(ApiEndPoint + '/' + post.id);}catch(err){alert('something failed while deleting a post !');this.setState({posts : originalPost});}
Expected And Unexpected Error
Expected Error
If we try to delete post with invalid id : it will return with an error 404 : Not found (which is a standard http error)
400 : when we try to submit a form with invalid data.
400 : range as CLIENT ERROR ; So we should display a specific message.
Unexpected Error
Network is down so we won’t be able to call to the server. or network is up but server is down or network is up server is up but database is down.or we have a bug in our application code
so we should display a generic or user friendly message.
catch(err){if(err.response && err.response.status === 404){alert("This post has been deleted alredy");}else{console.log("logging the error",err);alert("an unexpected error occured.");}}
Cconclusion
Keep Reading !
