Fetch() - The Basics
Tags: javascript, fetchapi, fetch
Published: 2020-12-19 07:22:16

The Fetch API provides an interface for fetching resources (including across the network).

For making an request and fetching a response, you need to use the **fetch()** method that provides an easy, logical way to fetch resources asynchronously across the network. 

*Example:* I'll demonstrate a basic fetch request using a dummy API from [Json Placeholder] (https://jsonplaceholder.typicode.com/users). This dummy API fetches a list of users with associated data.  
Have a look at the following code:
```js
  fetch('https://jsonplaceholder.typicode.com/users')
  .then(response => response.json())
  .then(data => console.log(data));
```
This will console log the data in following manner.
```js
{
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
      "name": "Romaguera-Crona",
      "catchPhrase": "Multi-layered client-server neural-net",
      "bs": "harness real-time e-markets"
    }
  }
...more user data
```

Here we are fetching a JSON file across the network and printing it to the console. The simplest use of fetch() takes one argument — the path to the resource you want to fetch — and returns a promise containing the response (a Response object).
This is just an HTTP response, not the actual JSON. To extract the JSON body content from the response, we use the json() method.


### Upload json data
Use fetch() to POST JSON-encoded data. Consider an example where you have updating their profile, you store that information in key:value pair in an object. You can send that post that object data.

```js
const data = { 
  username: 'example',
  email: 'johndoe@example.com',
  worksAt: 'exampleCompany',
  position: 'Designer'
};

fetch('https://example.com/profile', {
  method: 'POST', // or 'PUT'
  headers: {
    'Content-Type': 'application/json', // should match data you are posting
  },
  body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
  console.log('Success:', data);
})
.catch((error) => {
  console.error('Error:', error);
});
```


###Upload a file
Another common use case would be to upload a file. Files can be uploaded using an HTML <input type="file" /> input element, FormData() and fetch().

Example: You have an input field of type file which will be used to select a file to upload.
```js
const formData = new FormData();
const fileField = document.querySelector('input[type="file"]');

formData.append('username', 'abc123');
formData.append('avatar', fileField.files[0]);

fetch('https://example.com/profile/avatar', {
  method: 'PUT',
  body: formData
})
.then(response => response.json())
.then(result => {
  console.log('Success:', result);
})
.catch(error => {
  console.error('Error:', error);
});
```


In above example we got the uploaded file using **fileField.files[0]**, and appended that to **formData** object.
Finally in fetch's body key, we pass the formData object.

For more information on fetch API you can visit [MDN docs]
(https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch)