using fetch API in LWC

Let's look at how to make a callout using the fetch API in LWC

We usually use Apex to make callouts from Salesforce. To make call-outs from LWC components using Apex we need to use Apex Continuation. However, we can also use fetch API to make a callout from LWC and process the response.

In a way using fetch API to make a callout will be a lot easier and smoother than using Apex Continuation to make the callout.

Let us look at how to make a callout in LWC using fetch API.

Am assuming that you already know how to create a Lightning Web Component. Am not gonna walk you through the whole song and dance of opening VS Code, command pallet, SFDX command and etc.

Hope you too are cool with that :p

Here is the template file.

<template>
  <template if:true={repos}>
    <table>
      <tr>
        <th>Repo Name</th>
        <th>Description</th>
      </tr>
      <template for:each={repos} for:item="repo">
        <tr key={repo.name}>
          <td>{repo.name}</td>
          <td>{repo.description}</td>
        </tr>
      </template>
    </table>
  </template>

  <lightning-button label="Fetch Data" onclick={handleFetch}></lightning-button>
</template>
Template file of Lightning Web Component (exploreFetchAPI.html)

And this is the controller of the Lightning Web Component.

//exploreFetchAPI.js
import { LightningElement, track } from "lwc";

export default class ExploreFetchAPI extends LightningElement {
  @track repos;

  handleFetch() {
    let endPoint = "https://api.github.com/repositories?since=364";
    fetch(endPoint, {
      method: "GET"
    })
      .then((response) => response.json()) 
      /* response.json() gives us back a promise
      we need to process the promise in .then()*/
      .then((repos) => {
        this.repos = repos;
      });
  }
}
exploreFetchAPI.js

We are using promises here to handle the response that we got back from the callout. Usually, there will be some confusion as to why we need to use the second .then() in the JS file.

`response.json()` gives us back a promise and not JSON. Now we need to process the process again for which we would need the second .then() method.

In case you want to use Async Await with fetch API then this is for you, I tried rewriting the same functionality using Async Await.

//exploreFetchAPI.js
import { LightningElement, track } from "lwc";

export default class ExploreFetchAPI extends LightningElement {
  @track repos;

  async handleFetch() {
    let endPoint = "https://api.github.com/repositories?since=364";
    const response = await fetch(endPoint);
    const repos = await response.json();
    this.repos = repos;
    // console.log(repos);
  }
}
refactored exploreFetchAPI.js

Simple isn't it. Let me know what you think about this approach.