Misc. learnings. This page is currently under construction. 🚧
HTTP HEAD request
February 28, 2020
Some common HTTP requests are DELETE
, GET
, PATCH
, POST
, PUT
. However, there are other valid HTTP requests such as CONNECT
, HEAD
, OPTIONS
and TRACE
.
I learned more about HEAD
request while adding support for HEAD
requests to a GET
endpoint. An HTTP HEAD
request is similar to a GET
request but it only cares about the header response to a request and ignores the body that was sent. A HEAD
request can be made to determine whether or not a cache resource is stale or not or get additional information about a resource from its response headers alone (for e.g., it's size or whether or not it exists). Since a body isn't returned HEAD
requests require less bandwith than similar GET
requests.
Learn more at: HTTP - METHODS - HEAD | MDN
Finally(), I'll clean up my Promises!
February 25, 2020
When handling asynchronous operations sometimes it is necessary to update the state after the promise resolves regardless of it was successful or rejected. In order to avoid having to duplicate this cleanup code there's a handy method, finally()
that has a callback function that is executed once a promise settles by either being fulfilled or rejected. So if for example you want to update the loading
state from true
to false
after a promise settles regardless of the response was an error or not you can do something like.
fetch("https://dog.ceo/api/breeds/image/random")
// handle successful response
.then(response => response.json())
.then(json =>
this.setState(
{
imgUrl: json.message,
},
() => {}
)
)
// if there's an error log it!
.catch(err => console.log(err))
// once promise resolves loading should be set to false
// regardless of if data was returned or if there was an error
.finally(() => this.setState({ loading: false }))
Learn more at: Promise.prototype.finally() - JavaScript | MDN