Fetch API was bringing darkness to my codebase. So I did something to illuminate it.
Javascript’s fetch()
was a very good addition as it made http request handling a breeze for the developers without using any external libraries! But, everything come’s with it’s pros and cons.
For me, I was already using packages like axios
request-promise
and they worked great. But, when I came to work at my current workplace and seen the usage of fetch()
, I was not sure about the advantages or disadvantages at first. From one side, it was good as it removed the dependency on third party libraries. On the other side, the usage of fetch
didn’t feel intuitive and clean.
For example, here is a code snippet I totally hated:
Two things I didn’t like here at all.
- The
http status handling
orerror handling
- The
response.json()
call
Why do I have to call response.json()
every time I make a http request
! Most of the time we need the data
directly or an error
that can be handled with a catch
block.
And then comes the error handling
and http status handling
. The default .catch()
block won’t get http status code errors, it only gets the failed request
, network error
like errors.
SO, as developers (read magicians 😉) we either remove our hated things or we make them lovable !!!
But, making code lovable is not an easy task, especially when it’s not about functionality but more of a design/coding pattern related problem. So, It took me a few trials and errors to reach a medium satisfactory result!
Iteration 1: Cleaning
So as you can see, I just removed the callback code to a separate handler function checkStatus
which checks the status code and if any thing between 200
and 300
comes up, it throws an error.
I also moved response.json()
to a separate parseJSON
function which was invoked from a different .then
block to make it cleaner.
This was fine but not convincing enough for me!
Iteration 2: Reusability
Iteration 1 was looking fine, but still it wasn’t that reusable. So, I made a wrapper
/service
to make it reusable throughout the project. Let’s say it’s named as Fetcher
and exports this as the name from a file fetcher.js
. So, our service/wrapper looks like something below:
Now, we can simply import this anywhere in our project and use it like below:
We can also use async-await
instead of callbacks like —
This examples are just simple code snippets to demonstrate my approach, not any solid rules or anything. So, these can be transformed as your requirements. Also, for this easy task I didn’t see the usage of a package that provides this wrapper.
Happy Coding 😄
Related Resources —
Read more of my articles -
✉️ Subscribe to CodeBurst’s once-weekly Email Blast, 🐦 Follow CodeBurst on Twitter, view 🗺️ The 2018 Web Developer Roadmap, and 🕸️ Learn Full Stack Web Development.