How to make AJAX & API calls with Vue JS

  • 2019-03-19 06:32 AM
  • 358

Make AJAX & API calls with Vue JS

Recently, I have been seeing people asking how to handle AJAX requests and API calls with Vue.

At first, I didn’t really understand why people were confused about this because, this is not a Vue question but more of a JavaScript question.

Then… Illumination! I found out why people were so confused about this: 
It’s because Vue is very flexible and doesn’t have any rule for that and leaves the decision to you.

While this may be good for small projects, on medium-to-large projects, you need to know when and how to separate concerns.

Where can I do API calls? Mixins? Vuex Actions? Components?

If you just want the final answer, go to the next title.
If you want a detailed explanation to become a better developer, let’s see all the options with their pros and cons:

  • Mixins: You could put it in a shared mixin and import it when you need it
    • PROS: you only load when you need it
    • CONS: you have to add it as a method and therefore, mix concerns between methods used by the template and methods used for JS logic non related to the template
  • Vuex Actions: You could create a Vuex action for each AJAX request
    • PROS: It’s centralised and available in your components and can mutate global state
    • CONS: Well… You need to load Vuex lol. If your project doesn’t have the need for it, it’s a bit overkill to load it only for AJAX calls. Especially if you don’t commit mutations in your actions, in my opinion it becomes an 
      anti-pattern

How to make AJAX & API calls with Vue JS

From Vuex’s documentation
  • Components: You could directly make AJAX calls in the methods of your component
    • PROS: You just use what you need and have no overload
    • CONS: Your calls are scattered everywhere and it can become really hard to maintain. You can create code duplication if two components need the same API call

As you can see, all of them have pros and cons so which one is the best?
Well, none of them, or should I say: All of them?

This is not a Vue problem, it’s a JavaScript architectural problem.

The question you should ask yourself is: Are my API calls related to Vue? 
The answer is: No, they are related to your app.

Whenever something can be abstracted: abstract it!

The solution: Create a separate JS file that you import

The solution is in fact quite easy. Your API calls need to be centralised and reusable so, why not use something vanilla JS has : a class or object literal.

For each API resource, create an API file with an object literal or a static class or just export functions that make the API calls.

Why is this better?

  • If you need it in another project that isn’t a Vue project, well: it’s reusable ! It’s just a JS file, right?
  • If a path / url changes in the API, it’s centralised so no need to remember in which action it was called or in which component, just go to your API file and make the changes there :)
  • Abstraction is always better than tightly coupled logic

Here are some screens to understand what I’m saying.

How to make AJAX & API calls with Vue JS

This is a fresh install

How to make AJAX & API calls with Vue JS

This is the main.js file where I config axios, the AJAX library (it could be any other library or fetch API)

How to make AJAX & API calls with Vue JS

Here I’ve created a folder “services” and a sub folder “api” in which I have my API file for “Posts” which is basically just an object literal with methods that I export as default value of my file (ES Module)

How to make AJAX & API calls with Vue JS

Now, here’s how to make your API call in your component, it can be exactly the same in a Vuex action.

Well, I hope this was clear. API or GraphQL calls must not be directly coupled to Vue. They are independent and not tied to your view layer so you can abstract them.

Here’s a list of things I abstract on my medium-to-large Vue projects:

  • Custom validators
  • Api or other AJAX requests
  • Models (models here are not like back-end models, it’s more like a data formatter mostly used in API files to format data before I pass it to a component)
  • Utility functions (but most of the time I directly create them as mixins)
  • Analytics wrapper / Google Api Wrapper / Facebook Wrapper…
    Any non-related to Vue service I can have

Remember, those are just JS files, you can import them in components or Vuex stores or in Mixins and so on.

Example with Vuex store (EDIT)

How to make AJAX & API calls with Vue JS

Here’s my store with a namespaced module in it. No need to import my API handler in my component because it’s my store that imports it. Don’t forget to return promises in your actions so that you can chain when you use them later

Frameworks and libraries are good, but, JavaScript design patterns are better.

PRO TIP: another advantage with this, is that you can also import it in Vue-router navigation guards or any other library where you hook to and do some API calls :)

Learn More

Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Nuxt.js - Vue.js on Steroids
Build Web Apps with Vue JS 2 & Firebase
Vuejs 2 Authentication Tutorial
Async Vue.js Components
Build a Basic CRUD App with Laravel and Vue
Build a CMS with Laravel and Vue
Vue & Vuex: Structure Your App With Centralized State Management

Originally published by darkylmnx at https://itnext.io

Suggest