[Vuejs]-How to correctly make API calls inside store.js using Vuex to update data?

0👍

Look at this store from my real project. I’ve leaved comments to explain you some parts of the code:

import {
  PAGES_FIND,
  PAGES_FIND_ERROR,
  PAGES_FIND_SUCCESS,
} from '../mutation-types';
import { PagesAPI } from '../../api';

const state = {
  loading: false, // this is needed to show `loading` screen
  error: null,    // this is needed to store and show error to the user (API errors)
  pages: [],      // pages will be here after fetching
};

const mutations = {
  [PAGES_FIND](state) {
    state.loading = true;
  },
  [PAGES_FIND_SUCCESS](state, payload) {
    state.loading = false;
    state.error = null;
    state.pages = payload;
  },
  [PAGES_FIND_ERROR](state, payload) {
    state.loading = false;
    state.error = payload;
  },
};

const getters = {};
/**
 * All AJAX calls should be here. I prefer to use `axios` for this job. 
 * I will show you PageAPI later
 */
const actions = {
  /**
   * Fetches list of pages. Returns all the pages by default
   * @param {Function} [commit] - Commit function
   * @param {Object} [params={}] - Fetch params (it may be filter, limit, etc)
   * @returns {Promise}
   */
  fetchPages({ commit }, params = {}) {
    commit(PAGES_FIND); // we need to show 'Loading...' inside the component
    return PagesAPI.find(params)
      .then(res => commit(PAGES_FIND_SUCCESS, res.data))
      .catch(err => commit(PAGES_FIND_ERROR, err));
  },
};

const namespaced = true;

export default {
  state,
  getters,
  mutations,
  actions,
  namespaced,
};

PageAPI implementation is here. I like to separate this things to make the code in side actions easer to read:

/* eslint-disable import/prefer-default-export */
import axios from 'axios';
import config from '../../config';

const ENDPOINT = `${config.service.baseUrl}/pages`;

/**
 * Returns pages
 * @param {Object} params
 */
export const find = params => (
  axios.get(ENDPOINT, { params })
);

Leave a comment