DEV Community

Dane Dawson
Dane Dawson

Posted on

Fetch() in JavaScript pt. II, Revenge of the options

Where we last left off at my first post about fetch() we have the ability to use fetch to perform GET requests. For POST, PATCH, and DELETE, we will need to utilize the options I referred to in the last article.

let options = {
      method: "METHOD",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ dataKey1: dataValue1, dataKey2: dataValue2 }),
    };

There are numerous and nuanced ways to set up fetch requests, and for more detailed information I would recommend looking here, here, or googling around if you need a particular approach. This walkthrough is simply a very basic, functional application of CRUD functionality for fetch requests designed to introduce new programmers and open the door to the possibilities of fetch().

Let me try to break down what each of those aspects can be used for

let options = {
      //This is where you specify what type of request you are sending.
      //This article will cover a basic application of POST, PATCH, and DELETE
      method: "METHOD",
      //I only got the kind of graze the surface of what headers do. 
      //From my understanding they are a way for the backend and front end
      //verify they are sending the same type of information in the same way.
      headers: { "Content-Type": "application/json" },
      //This is the actual content you are sending, you can think of it as either
      //a ruby hash or a JavaScript object (the latter is more accurate). Fetch
      //exchanges JSON strings of data, so we have to convert our data object
      //into a JSON string.
      body: JSON.stringify({ dataKey1: dataValue1, dataKey2: dataValue2 }),
    };

This is the basic outline of what all three of these fetch functions will look like, with some minor alterations depending on what the function is.

POST

The following is an example of one way you could set up a POST request to a simple backend API to create a new user.

//setting global constant for the user database URL
const userURL = "https://localhost:3000/users"

//This is the user object we are adding to the database. 
//This model is fairly simple, but it could contain as many attributes as you would like.
let user = {
  name: 'Mordecai Phineaus III',
  email: 'mordiphi@gmail.com'
};

//by creating the postOption as an object, it makes it easier to call within the fetch
let postOptions = {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  },
  body: JSON.stringify(user)
});

fetch(userURL, postOptions)
//Note: the following code is functionally identical to the fetch above
fetch("https://localhost:3000/users", {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  },
  body: JSON.stringify({
  name: 'Mordecai Phineaus III',
  email: 'mordiphi@gmail.com'
  })
})
//You can see how it can be easier to follow if you use variables

PATCH

Recent updates to Rails and JavaScript have made a PATCH request much simpler. If the back end is properly set up all you have to do is target the object you want to alter and send a similar options object as the POST. See the differences below.

const userURL = "https://localhost:3000/users"

//For this example, let's imagine this is the model for the user object we are updating.
//For simplicity it only has an id, a name, and an email
user = {
  id: 1
  name: 'Mordecai Phineaus III',
  email: 'mordiphi@gmail.com'
};

//Our user wants to update their email
newEmail = {
  email: 'MightyMordiPhineas@gmail.com'
}
//As we are only updating the email, we don't need to include any other attributes

//New PATCH request with the updated email as the body
let patchOptions = {
  method: 'PATCH',
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  },
  body: JSON.stringify(newEmail)
};
//We will need to find the user in the database to update them
let userId = user.id
//Now we fetch to the specific id of the model we are trying to update

fetch(userURL+'/'+userId, patchOptions)

//Note the above single line of code is functionally identical to the following
fetch("http://localhost:3000/1", {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
    },
  body: JSON.stringify({
      email: 'MightyMordiPhineas@gmail.com'
        })
  };
);

DELETE is even easier. This is by far the most dirty and straightforward way to do a delete, but especially for your first delete interactions it will work great!

let patchOptions = {
const userURL = "https://localhost:3000/users"

//Let's take a look at that user we had before
//note the updated email address as our PATCH was so successful
user = {
  id: 1
  name: 'Mordecai Phineaus III',
  email: 'MightyMordiPhineas@gmail.com'
};

//Now we just want to delete the file entirely. 

//Since no specific information is needed to delete the file other than the user id
  let userId = user.id

//Our DELETE option is far cleaner
let deleteOptions = {
  method: 'DELETE',
};
//Again, we just target the user by their id we captured above
fetch(userURL+'/'+userId, deleteOptions)

Hopefully armed with these base outlines you can get your API and client side connected and start to really explore the potential programming has to offer.

Until next time, happy coding!

Discussion (0)