Everything You Need To Know About .Fetch()
Tags: beginners, webdev, javascript, programming
Published: 2022-02-16 04:31:39

## What is Fetch()?

We can interact with data inside of our JavaScript file pretty easily, but what about data outside of our JavaScript file? In order to interact with and manipulate data from an outside source, like an API or other server, we use <code>Fetch()</code>. <code>Fetch()</code> is a method in JavaScript that allows us make a request to a server.
## Using Fetch()

```JavaScript

function getData() {
    fetch(url)
    .then(response => {
        //function for when the response is received
    })
   

}
getData()
```

The code above shows how you would make a GET request using <code>Fetch()</code>. When we make a request to a url there will be a delay that takes longer than the amount of time it would take for our code to execute. Due to that slight pause the code needs to wait while that promise is being met. Using <code>.Then()</code> and <code>.Catch()</code> allow the callback functions to only execute once the promise is met or errors out. Once the promise that <code>Fetch()</code> makes is met, <code>.Then()</code> is passed a response depending on the endpoint of the url. This response isn't something we can directly interact with using Javascript so to fix that it needs to be converted to JSON.


```JavaScript

function getData() {
    fetch(url)
    .then(response => response.JSON())
    .then(responseArr => {
        //function to manipulate JSON data
    })
    
}
```

### What is JSON?
JSON is short for JavaScript Object Notation and it is a format of data easily manipulated by JavaScript. It is important to know however that Javascript is not the only programming language that can use JSON data. 

A JSON file might look something like this:
```JavaScript
[
    {
        'Name': 'Todd',
        'Age': 17,
        'Friends': [
            'Alex',
            'Rebecca',
            'Sam'
        ]
    }
    {
        'Name': 'Amanda',
        'Age': 32,
        'Friends': [
            'Michael',
            'Brett',
            'Nita'
        ]
    }
]
```
JSON data is basically a bunch of javascript-like objects inside of an array. .JSON() that was used in the first <code>.Then()</code> function is a built in method that converts the readable stream passed into it by the promise into JSON. 

After the promise is made into JSON data we're then able to pass that JSON array into another <code>.Then()</code> function.

## Handling errors
```JavaScript

function getData() {
    fetch(url)
    .then(response => response.JSON())
    .then(responseArr => {
        //function to manipulate JSON data
    })
    .catch(error => {
        //function to handle error
    })
    
}

```
Some times our <code>Fetch()</code> function will error out, this is when the <code>.Catch()</code> function executes it's code. It is however very uncommon for <code>Fetch()</code> to error out, the only thing that won't return a promise is a network issue.<br>

As a side note while it isn't required to use arrow functions and callback functions I find it a lot cleaner and helps me write more simple DRY code.Instead of writing out something like: 

```JavaScript
.then(response => response.JSON())
.then(response, function(response) {
    //function to handle the response
})
```
You can use callbacks and arrow functions to simplify your code and insure each function is single purpose like this:
```JavaScript
.then(response => response.JSON())
.then(callBack())

callBack(arr) {
    //function to manipulate data in JSON array
}
```
## HTTP Verbs

The examples above have all shown how you can get data from a server, but retreiving data isn't the only way we need to be able to interact with data. What if we need to delete data? What if we need to add data to our database? There are four basic actions we could expect to do with our data- create, request, update and delete or CRUD for short. Each letter in CRUD represents a different HTTP verb. You can think of HTTP verbs as ways to desribe the action our fetch is doing, or as each verb representing a different part of CRUD. <code>Fetch()</code> by default will assume you want to make a GET request to the url that is passed in. The other HTTP verbs are POST, PUT and DELETE. Each verb will represent either creating, reading, updating or deleting data from your database. Since <code>Fetch()</code> defaults to using GET you don't have to specify which kind of request you're making, however with all of the other verbs you will need to tell the function which kind of request you want to make. 

POST - CREATE <br>
GET  - RECEIVE <br>
PUT - UPDATE <br>
DELETE - DELETE <br>




## GET
As I said earlier GET is the default HTTP verb that is used when using <code>Fetch()</code>. GET in my opinion is the easiest of the verbs to understand and is definitely the simplest to write. You pass <code>Fetch()</code> a url and use <code>.Then()</code> to add asynchronous functions to operate over the data returned after the promise is met.

```JavaScript
function getData() {
    fetch(url)
    .then(response => response.JSON())
    .then(callBack())//callback funcion to handle data from response
    .catch(error => {
        //function to handle error
    })    
}
function callBack(arr) {
    ///function to manipulate JSON array
}
```
This function is similar to one of the examples from above. The function <code>getData()</code> fetches data from a url, then passes that response into an arrow function that converts the readable stream response into a JSON array that we can iterate over and manipulate using JavaScript. 

## Headers
We use headers when using <code>Fetch()</code> to define certain parts of the request that might differ for each request. GET doesn't require a header but for every other HTTP verbs we use a header to tell our browser what kind of request we're making. Inside these headers we include things like what kind of request we're making, what parts of the data is being changed and what format new data is if necessary. Every HTTP verb will require different content inside of the header, for example POST requires the method as well as what format our data will be sent in looking something like this:
```JavaScript
fetch(url, {
    method: 'POST',
    headers: {
        'content-type': 'application/JSON',
        Accept: 'application/JSON'
    },
    body: JSON.stringify(newData)
}

```


## POST
POST is used to create or add data to the database. As you saw in the examples above you make a POST request by defining POST as the method in the header object. You will also need to define what format the data you're sending is coming in. Inside the headers value will be another object defining that format. Then in the body value you define what it is you'll be adding to the database. You'll need to convert the data into a JSON string to make the request.


```JavaScript
let newData = {
    key1: 'value1',
    key2: 'value2'
}

function addData(){
fetch(url, {
    method: 'POST',
    headers: {
        'content-type': 'application/JSON',
        Accept: 'application/JSON'
    },
    body: JSON.stringify(newData)
})
.then(response => response.JSON())
.then(responseArr => /*function to handle data on client side*/ )
}
```

## PATCH
PATCH is used to make changes to existing data. PATCH will require you to define it as the method and it will also require you to define headers and a body. There is another HTTP Verb 'PUT' that can also be used to update data. PUT is best if the whole object you're targeting needs to be edited or changed as you'll have to pass a whole new object to replace what you're changing anyways. PATCH only requires you to specify the new value of the key you're changing in the object and that's all that will be updated.

Just like POST you'll need to define what the format for the data that you're sending is coming in, as well as make sure that you're sending the data in that format. 
```JavaScript

let newData = {
    key4: 'value4'
}

function changeData(){
    fetch(url, {
        method: 'PATCH',
        headers: {
            'content-type': 'application/JSON',
            Accept: 'application/JSON'
        },
        body: JSON.stringify(newData)
    })
}
```


## DELETE
DELETE is used to delete data from the database, other than GET this is probably the most straight forward <code>Fetch()</code> request to make. DELETE will remove all of the data depending on the id of the data that needs to be deleted. You don't need a header on a DELETE request, you just need to specify the method that you want to use and pass in a url with an endpoint that points to the id of the data to be removed. This would look something like this:
```JavaScript
function deleteItem() {
    fetch(url, {
        method: 'DELETE',
    })
    .then(response => response.JSON())
    .then(obj.remove())
}

```
## Summary
<code>Fetch()</code> is important to understand as it allows us to interact with data not inside our JavaScript file. CRUD describes the four different uses for <code>Fetch()</code> and the four HTTP verbs that we can use with <code>Fetch()</code> to make requests. It's important to remember what each step of the function actually returns and passes to the next <code>.Then()</code>, use <code>console.log()</code> to make sure you're getting what you expect if you aren't sure. 

Here are some more resources you might find useful to learn more about using <code>Fetch()</code>, CRUD, HTTP verbs, and promises in JavaScript:

[https://developer.mozilla.org/en-US/docs/Web/API/Response](https://developer.mozilla.org/en-US/docs/Web/API/Response)<br>
[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)<br>
[https://www.javascripttutorial.net/javascript-fetch-api/](https://www.javascripttutorial.net/javascript-fetch-api)<br>
[https://developer.mozilla.org/en-US/docs/Glossary/CRUD](https://developer.mozilla.org/en-US/docs/Glossary/CRUD)<br>
[https://www.tjvantoll.com/2015/09/13/fetch-and-errors/](https://www.tjvantoll.com/2015/09/13/fetch-and-errors)<br>
[https://learnwithparam.com/blog/how-to-handle-fetch-errors/](https://learnwithparam.com/blog/how-to-handle-fetch-errors/)<br>
[https://stackoverflow.com/questions/6203231/which-http-methods-match-up-to-which-crud-methods](https://stackoverflow.com/questions/6203231/which-http-methods-match-up-to-which-crud-methods)<br>