Using Fetch API in Vue 3 Composition API

Using Fetch API in Vue 3 Composition API

Composition API (Application Programming Interface) was released when Vue 3 was introduced as a way to improve the already existing options API of Vue.

In this tutorial, you will learn how to communicate with an API in a Vue Composition API setup function with the Javascript fetch API.

Note: Some familiarity with Vue and the Vue Composition API is assumed, but there will hopefully be some useful takeaways regardless of your framework choice.

Prerequisite

To follow through this tutorial, you are required to;

  • have node installed on your computer

  • have a Vue 3 app running (refer to the docs)

What is Fetch API?

Fetch API provides an interface for handling requests and response resources in Javascript applications. Fetch API provides a single logical place to define HTTP-related concepts such as CORS and extensions to HTTP. It provides a powerful and flexible feature set as opposed to XMLHttpRequest.

The keyword of the Fetch API is fetch.

fetch('url', {options})

The fetch API accepts two parameters, the URL (Uniform Resource Location) and options. It is important to know that the options parameter is optional and is not always required in the fetch API function. Some of the parameters accepted in the options object include method, mode, cache, credentials, headers etc.

What is Composition API?

When the term Composition API is mentioned in Vue, reactivity comes to mind. Composition API allows you to directly create a reactive state, computed state, and watchers. Since its introduction to VueJS, Composition API introduces some important improvements that make work easier and improve the readability of our VueJS code.

Composition API allows you to write reactive code anywhere in your application and allows you to pull some reactive logic outside of the component.

Implementing Fetch API in Composition API setup()

According to the VueJS docs, the setup() hook serves as the entry point for Composition API usage in components in the following cases:

  1. Using Composition API without a build step;

  2. Integrating with Composition-API-based code in an Options API component.

The basic syntax of a composition API is as follows;

<script>
import { ref } from 'vue'

export default {
  setup() {
    const data = ref({})
    return {
      data
    }
  },
}
</script>

In the above code, data is returned as a ref which is shallow unwrapped data so you don't have to access it with .value. It can be automatically accessed with the javascript this keyword.

setup() should always return an object so that the single file reactive data is exposed for access in the file.

Fetch API x Composition API

Let's attempt to combine both API usage in a single file. In this example, I will use a random joke API as the sample API.

<script>
import { ref } from 'vue'

export default {
  setup() {
    const data = ref({})
    return {
      data
    }
  },
  async created() {
    await fetch("https://api.chucknorris.io/jokes/random", {
        method: 'GET' //optional
    })
      .then(async (response) => {
        const data = await response.json()
        console.log("data", data);
        this.data = data
      })
      .catch((error) => {return error})
  },
}
</script>

Here, I am using the Vue created hook to fetch our data. I am using the async and await to make sure the API request is resolved before assigning our response to our reactive data object also the Promise object is used to represent the eventual completion (or failure) of our asynchronous operation and its resulting value.

Conclusion

There are several other methods of communication with API in Vue. This tutorial has discussed the Fetch API which is one of the methods of communication with API in Javascript.

I hope you’ve enjoyed reading through this tutorial. If you have any questions, leave them in the comments section below. I’ll be happy to answer every one of them.