DEV Community

marknosal
marknosal

Posted on • Updated on

Fetch Requests with Javascript

0. Intro

Fetch requests are an important skill to master because it will make any full stake application you write able to save, read, edit, and delete data. Your application's ability to communicate with servers (or your server) is paramount. They are pretty simple once you see a few examples, but there are things you need to be wary about, such as their asynchronous nature.

1. Basics of the Fetch

At the base of fetch requests is the ability to standardize the way your web applications make/receive HTTP requests to/from servers. Its a line of communication from the client-side (ex. your browser) and the server-side (ex. Facebook's data centers). Some key components are:
A)URL or Uniform Resource Locator which specifies the location or server's endpoint where the data your trying to interact with is located.
B)(HTTP) Method this what I like to call a computer verb. It's what the computer is supposed to do with the fetch request. The most common you'll run into are GET(retrieving data), PATCH(updating existing data), POST(creating new data), and DELETE(removing data). There are other's but I won't get into them here.
C)Headers are used to describe additional info about your fetch request. They are used to help the server know what types of data to expect, credentials of the request's origination, etc/
D)Body, this is only for non GET requests. It contains data that is sent to the server. Useful if you are creating a new data record (uploading a picture, creating a username, etc)
Super Vanilla Example:

Image description

This is the most basic example of a fetch request I could think of, it only includes the URL. By default this making a GET request. It is asking only to retrieve the data located at the URL. It then converts the servers response to JSON, and finally console logs the data for you to see in the DOM or (if something went wrong) console logs the error.

2. Implementing Fetch Requests

I'll go over some examples of using fetch in a React component each of the other HTTP methods I listed (POST, PATCH, DELETE). All will be as vanilla as possible, but they'll be taken from code I've already written so they'll have real world functionality and not just used for examples (like Super Vanilla)

A)POST

Image description

Here you'll see the fetch is made to '/customs'. You'll see the method is POST because I'm sending data to the backend that I want the server to save or commit to moemory. Headers is the next few lines. The first is Accept, which lets the server know the data type the client (my DOM) can handle/is expecting(in this case, JSON). The Content-Type is the reverse. It's letting the server know that the data I'm sending is in JSON format. The body is the last part of the fetch request is the body. In this specific case I'm sending a key/value that I want saved in the server. JSON.stringify is used to convert a Javascript object or value into a JSON string representation. Its used to be stored as a string. JSON is useful because it is extremely lightweight and easy for humans to read.
That's it for the response. After that, in the then statements, the front end code is converting the servers response to json and then either logging the data if it was a successful request or logging the error to help me debug the code.

B)PATCH

Image description

Here's an example of a PATCH request. It works VERY similar to a POST, but I've sent it to a more specific endpoint in '/customs'. Its used for editting already existing data. In this case I have the id for the 'custom' record I'm trying to update. 'values' represents a prop that was passed into the submit function which this fetch request is contained in. In this specific case it is key/value of the specific custom's notes attribute ({'notes':'some note'}). If successful it will save the custom.notes to the value that is being sent. It can be used to dynamically update any custom's note attribute to a new value.

C)DELETE

Image description

This is the second easiest method besides GET. headers are not required and neither is a body, or handling a response for that matter (unless you coded it that way). You could send it to a specific record like I did for the PATCH and it would permanently delete the record located there. But for my specific case, I have it used to remove the current 'user_id' from the session aka logging out the current user.

3. Summary

To conclude, making fetch requess is a necessity for dynamic full stack applications. Some things that make them important are:
A)The standard communications between your laptop and the servers your applications communicate with
B)The asynchronous nature is allows your applications to flow smoothly and not be held up on a long loading screen while your waiting for your photos/data to load.
C)Since they return responses(or rather a promise that results in a response) it allows the engineer to handle the logic flow.
D)It can allow you to catch and handle errors in a specific or umbrella manner

Good luck!

Top comments (0)