1

I'm just wondering if there is currently a consensus within the Vue.js community as to which life cycle hook to use for dispatching an API fetch action?

For example, I have an action such as in my Vuex store:

  ...
  actions: {
    fetchAccount: async ({ commit }, payload) => {
      await Vue.prototype.$API.fetchAccount(payload).then((response) => {
        commit("SET_ACTIVE_ACCOUNT", response.data);
      });
    },
  }
  ...

The action gets passed off to a service:

import { axios } from "@/services/http";
import { EventEmitter } from "events";

class accountServiceAPI extends EventEmitter {
  constructor() {
    super();
    this.accessToken = "";
  }

  fetchAccount(payload) {
    return new Promise({resolve, reject} => {
      axiosWave.get(`api//v2/accounts/retrieve/${payload.accountUUID}`, { headers: {} }).then(response => {
        if (response.success) {
          resolve(response.data);
        } else {
          reject(response.data);
        }
      }).catch(error => {
        reject(error.response);
      });
    });
  }
}

const accountServiceAPI = new accountServiceAPI();

accountServiceAPI.setMaxListeners(5);

export default accountServiceAPI;

I usualy dispatch this off in the created() life cycle hook for the component that the data is required to be for...but surely there must be a more performant way?

Micheal J. Roberts
  • 3,735
  • 4
  • 37
  • 76

1 Answers1

1

You can fetch from API and manipulate your data/state as early as in created(). mounted() is called when the instance has already, well, mounted or rendered. You'll usually do UI-related setup here.

Also, you can improve the fetchAccount action like so:

fetchAccount: async ({ commit }, payload) => {
  const { data } = await Vue.prototype.$API.fetchAccount(payload);
  commit("SET_ACTIVE_ACCOUNT", data);
}
Alfonz
  • 1,010
  • 13
  • 26