Basics

The syntax for fetch is simple: fetch(path to what youre fetching, parameters for request)

It returns a promise, which functions as a placeholder for the eventual response we get asynchronously.

The promise can be manipulated with .then().

You pass .then() a function.

<script>
document.getElementById("button").addEventListener("click", getText);
functiongetText(){
  fetch("sample.txt")
  .then(function(res)
  {console.log(res);}
  );}
  </script>

This logs the result from a text file.

The log looks like this in the console:

Response {type: "basic", url: "http://127.0.0.1:5500/sample.txt", redirected: false, status: 200, ok: true, …}body: (...)bodyUsed: falseheaders: Headers {}ok: trueredirected: falsestatus: 200statusText: "OK"type: "basic"url: "http://127.0.0.1:5500/sample.txt"__proto__: Response

You add a method to the response (.text(), .JSON(), etc) to format the response into the data you need.

After asking the console to log res.text() from the previous example, this is what the console says:

Promise {<pending>}__proto__: Promise[[PromiseState]]: "fulfilled"[[PromiseResult]]: "I am sample txt file"

You often chain together the then()s to prepare the data.

function getText() { 
  fetch("sample.txt") 
  .then(function (res) { return res.text(); }) 
  .then(function (data) { console.log(data); }); }

Now the console logs the text itself.

Cleaned up with arrows:

fetch(sample.txt) .then((res) => res.text()) .then((data) => console.log(data));

Catching Errors

Just add .catch in the string of .then's.

.catch(err => console.log(err))

Configuring the fetch request

There's a second parameter you can use to configure the API call, etc.

fetch('route', {object that specifies if it's a POST request, etc})

Code Example

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"
      integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2"
      crossorigin="anonymous"
    />
  </head>
  <body>
    <div id="container">
      <h1 class="display-4 mb-4">Fetch API Sandbox</h1>
      <div class="d-flex">
        <button id="button" class="btn btn-primary mr-4">
          Fetch Text Data
        </button>

        <button id="getUsers" class="btn btn-success mr-4">Fetch JSON</button>

        <button id="getPosts" class="btn btn-warning mr-4">
          Fetch API Data
        </button>
      </div>
      <div class="form-group"></div>
      <form id="addPost">
        <div>
          <input
            class="form-control"
            type="text"
            id="title"
            placeholder="Title"
          />
        </div>
        <div>
          <input
            class="form-control"
            type="textarea"
            id="body"
            placeholder="Body"
          />
        </div>
        <div>
          <input class="btn btn-primary" type="submit" value="submit" />
        </div>
      </form>
      <div id="output"></div>
      <div id="output2"></div>
      <div id="posts"></div>
    </div>
    <script>
      document.getElementById("button").addEventListener("click", getText);
      document.getElementById("getUsers").addEventListener("click", getUsers);
      document.getElementById("getPosts").addEventListener("click", getPosts);
      document.getElementById("addPost").addEventListener("click", addPost);
      function getText() {
        fetch("sample.txt")
          .then((res) => res.text())
          .then((data) => (document.getElementById("output").innerHTML = data))
          .catch((err) => console.log(err));
      }

      function getUsers() {
        fetch("users.json")
          .then((res) => res.json())
          .then((data) => {
            let output = `<h2>Users</h2>`;
            data.forEach(function (user) {
              output += `<ul class="list-group mb-3">
                          <li class="list-group-item">${user.name}</li>
                          <li class="list-group-item">${user.email}</li>
                          </ul>`;
            });
            document.getElementById("output").innerHTML = output;
          });
      }

      function getPosts() {
        fetch("http://jsonplaceholder.typicode.com/posts")
          .then((res) => res.json())
          .then((data) => {
            let output = `<h2>Posts</h2>`;
            data.forEach(function (post) {
              output += `<div class="card card-body mb-3">
              <h3>${post.title}</h3>
              <p>${post.body}</p>
              </div>`;
            });
            document.getElementById("posts").innerHTML = output;
          });
      }

      function addPost(e) {
        e.preventDefault();
        let title = document.getElementById("title").value;
        let body = document.getElementById("body").value;
        fetch("http://jsonplaceholder.typicode.com/posts", {
          method: "POST",
          headers: {
            Accept: "application/json, text/plain, */*",
            "Content-type": "application/json",
          },
          body: JSON.stringify({ title: title, body: body }),
        })
          .then((res) => res.json())
          .then((data) => console.log(data));
      }
    </script>
  </body>
</html>