While there are other ways to get data to your web application, the fetch method is very convenient and purpose-built for doing so. At first, making simple fetch requests may seem intimidating. There are a number of moving parts (i.e. URL, method of request, headers, request body, etc) that make up a complete request and remembering how to manipulate them can feel a bit daunting. Documentation provided by any API’s that you may be interfacing with can hopefully make that process much more accessible than at first glance, but this ease of access, however, is not always made readily available so be prepared to fight a little bit to get access set up properly.
Beyond wrapping the various bits of intel into variables, utilizing the ability to implement callback functions is a great way to make your code more flexible and reusable when you know you will always be doing something with the response, but that what you do with it could vary. The example GET request provided below was actually refactored when I realized that I had just wrote a nearly identical block of code. At that point, abstraction came to the rescue and provided a way for that to be written neatly and concisely, and the smell coming from my code lessened for the time being. Notice that as long as we provided the ID of the object in question, in addition to the specific function we wanted to invoke with the response object, we were able to run a fair amount of code with a relatively few amount of lines, and it set us up to use the same model again in the future should we have a need to do so.
Additionally, the code above could be refactored to where the #getOnePup function takes in an additional argument (the baseURL, or pupUrl in this case) and have the second .then( ) function removed. This function could then be passed around and invoked very easily and dynamically, with the further ability to then become the direct starting point for a method chain to manipulate the data returned without even needing to begin a new line of code.
As your HTTP requests begin to grow in their complexity, remember to keep these ideas of abstraction and use of variables to make things neater, more “readable” for the next person, and hopefully more efficient. As your requests begin to take into account error handling, be sure to also break out that functionality. While this particular application of “tidying up” a more complex fetch request may beg to be broken out into other functions sheerly based upon the size of the workload being placed on a single function being too great to be practical, we can sometimes forget to do so when we get caught up in the moment. These cases will hopefully be prime for the picking when you take a look back over your code to give everything a light refactoring polish before calling the final product finished.