Fetch() in JavaScript pt. II, Revenge of the options
Tags: javascript, post, patch, delete
Published: 2020-04-25 23:57:01

---
title: Fetch() in JavaScript pt. II, Revenge of the options
published: true
description: Using fetch() for POST, PATCH, DESTROY requests
tags: javascript, POST, PATCH, DELETE
---

Where we last left off at [my first post about fetch()](https://dev.to/danedawson/introduction-to-fetch-in-javascript-2imd) 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.

```JavaScript
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](https://javascript.info/fetch), [here](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch), 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

```JavaScript
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.
```JavaScript
//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.

```JavaScript
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!

```JavaScript
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!