API Integration: Using JavaScript Fetch with Ionic 4.

When it comes to making HTTP requests inside of JavaScript, you can use a variety of different options. For example, you can use XMLHttpRequest, a third party library like Axios, or, fetch.

What exactly is Fetch?

Fetch is a promise based HTTP request API built in to JavaScript. It’s fairly well supported (87%+) and is promise based for ease of use and is a perfect fit for those wanting to use out of the box solutions for HTTP.

Let’s take a look at a few different ways we can use fetch to access data from the JSON Placeholder API:

GET

fetch(`https://jsonplaceholder.typicode.com/posts`)
    .then(res => res.json())
    .then(posts => console.log(posts))

The above fetch call has three key parts.

1. We're calling `fetch` with an API and this defaults to a GET request, returning a promise.
2. This returns us a HTTP Response, and as we're only interested in the **body** of that response, we call res.json() to extract this.
3. As we now have the **data** from our API call, we can perform any action we want on it.

When it comes to other HTTP verbs such as POST/PUT/DElETE, the process is quite similar:

Customisation

Let’s use fetch to create a new post by using HTTP POST. This starts by creating the actual post:

const newPost = {
    title: 'All about Fetch!',
    body: 'Fetch is awesome!'
}

We can now pass an options parameter into our fetch call, so let’s make that:

const options = {
    method: 'POST',
    body: JSON.stringify(newPost),
    headers: new Headers({
        'Content-Type': 'application/json'
    })
}

The options can then be passed along to our request like so:

fetch(`https://jsonplaceholder.typicode.com/posts`, options)
    .then(res => res.json())
    .then(posts => console.log(posts))

We can continue to customise this by adding more items to our options object, and subsequently changing the method to other values such as PUT or DELETE. Here’s an example:

const options = {
    method: 'PUT',
    cache: 'no-cache',
    body: JSON.stringify(newPost),
    headers: new Headers({
        'Content-Type': 'application/json'
    })
}

Ionic

Let’s put this together with an Ionic and Vue application. If you haven’t seen how to get started with Ionic and Vue, check out the following article: Ionic Angular, Vue and React.

New project

Let’s start off by creating a new Vue project. Run the following in your terminal:

# Ensure you have the Vue.js CLI installed
$ npm install @vue/cli

# Create a new Vue project
$ vue create ionic-fetch

> select default options

# Change directory into ionic-fetch
$ cd ionic-fetch

# Run the project
$ npm run serve

Inside of App.vue, we can go ahead and make a new function named getTodos that gets data from an API. In our case, we’re using the JSON Placeholder API available here: JSON Placeholder

export default {
  name: "app",
  data() {
    return {
      todos: []
    };
  },
  methods: {
    async getTodos() {
      const res = await fetch(`https://jsonplaceholder.typicode.com/users`);
      this.todos = await res.json();
    }
  },
  created() {
    this.getTodos();
  }
};
</script>

Whilst the data is loading, it’s good practice to show a loading state for the UI. I’ve elected to use ion-skeleton-text here and you can find out more about this with the following article: Ionic 4.1: Skeleton Text

We can then display this data inside of an ion-list:

<template>
  <ion-app>
    <ion-header>
      <ion-toolbar color="primary">
        <ion-title>ion-fetch</ion-title>
      </ion-toolbar>
    </ion-header>
    <ion-content>
      <ion-list v-if="this.todos.length <= 0">
        <ion-item v-for="i in 10" :key="i">
          <ion-skeleton-text animated/>
        </ion-item>
      </ion-list>
      <ion-list v-else>
        <ion-item v-for="user in this.todos" :key="user.id">{{user.name}}</ion-item>
      </ion-list>
    </ion-content>
  </ion-app>
</template>

Tada! Here’s our final project:

Ionic and Fetch

Quite fetching!

For a full list of these and more information on how to use fetch, I recommend checking out the MDN documentation on this topic.