Explanation of a Simple Fetch Request

Hello my name is Gene Campbell III, and I’m currently in Mod 3. We’re were introduced to JavaScript. Anyone who has worked with JavaScript before knows just how important fetch request are.

Here is a simple fetch request to retrieve information from a back-end rails server. The method is “fetch()”. The argument in the parameter is the desired location of the json db or api. The first thing a fetch returns is a promise containing the response. The promise isn’t in a format for us to manipulate yet, which is why we must call another “.then”. The promise is only an HTTP response not JSON. To extract the JSON body from the response, we use “.json()”. After calling this method, we know how have access to the JSON data. Usually most fetch requests use “data” where I have “bakes”. You can use any variable name you would like. Most JSON responses contain an array of hashes or more than one object. If it’s an Array, we can use the “.forEach” to iterate through each bake. We now have access to every instance of bake. RenderBake(bake) is a method I created to render a single bake element on my application. It is always good practice to use console.log or debugger in the second .then to figure what exactly your returned data looks like. You will also have an understanding of how to access each end-point.

This is what the response looks like in the db browser console. You can always verify the information is correct by visiting the desired fetch path yourself like such..

As you can see our information matches up, and we now how access to the information or database in the back-end in our front-end. I usually visit the url path before I even make the fetch request to ensure the target information is present. I hope this helps explain how a simple fetch “get” request works. You can also use “post” to create new objects into the database, and “patch” to update objects. The syntax is a little more complicated and different for a post and patch request. This article focuses solely on a get request. Thank you for reading.

Full Stack Software Engineer