What is the most efficient approach to completing everyday tasks directly in a Vuex store?

Currently, I am working on making API calls from within a Vuex store action object. Here's an example of one of my actions:

/**
 * Check an account activation token
 *
 */
[CHECK_ACTIVATION_TOKEN] ({commit}, payload) {
  Api.checkActivationToken(payload.token).then((response) => {
    if (response.fails()) {
      return commit('NEW_MESSAGE', {message: responses.activation[response.code]})
    }

    return commit('SET_TOKEN')
  })
}

I have multiple methods like this for different actions. What I want to do is display a loader while each API call is in progress and hide it once the response is received. One way to achieve this is by including the loader logic in each action like this:

/**
 * Check an account activation token
 *
 */
[CHECK_ACTIVATION_TOKEN] ({commit}, payload) {
  commit('SHOW_LOADER')
  Api.checkActivationToken(payload.token).then((response) => {
    commit('HIDE_LOADER')
    if (response.fails()) {
      return commit('NEW_MESSAGE', {message: responses.activation[response.code]})
    }

    return commit('SET_TOKEN')
  })
}

However, having to add these SHOW_LOADER/HIDE_LOADER commits in every API call is repetitive. I would prefer to centralize this functionality so that the loader handling is automatically applied to all API calls without the need for additional lines in each action.

The API I am using is a client layer built on top of Axios. I tried importing the store into the client layer or where the Axios events are triggered to handle the loader visibility centrally, but encountered a circular reference issue because of how the client layer is instantiated within the vuex module.

Is there a way to achieve what I'm aiming for through hooks or events that I may not be aware of?

Answer №1

After coming across a discussion on GitHub and hearing Evan You's thoughts on decoupling, I decided to take a different approach to addressing this particular issue.

I realized that by making the API layer directly dependent on the store, I was creating tight coupling between the two components. As a result, I opted to handle the SHOW and HIDE functionality within each component where the store commits are triggered. Here's an example:

/**
     * check the validity of the reset token
     *
     */
    checkToken () {
      if (!this.token) {
        return this.$store.commit('NEW_MESSAGE', {message: 'No activation token found. Unable to continue'})
      }

      this.showLoader()

      this.$store.dispatch('CHECK_ACTIVATION_TOKEN', {token: this.token}).then(this.hideLoader)
    },

In my case, I created methods in a Master Vue component that other components could inherit from, bypassing direct Vuex commits. This allowed me to trigger showLoader when necessary and manage the completion process with promises, calling hideLoader accordingly.

By doing this, I successfully removed presentation logic from both the store and API layers, keeping them separated in their respective domains.

If anyone has alternative suggestions or insights on this matter, I am open to hearing them.

Special thanks to @wostex for contributing to the conversation!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Import Vue filters directly into the component specifically

I have a central filters file that contains multiple filters and I want to import only one specific filter into my component. Here is an example of what my filters file looks like: //filters.js import Vue from 'vue'; Vue.filter('shorten&ap ...

Ensure the computed variable is always up-to-date using Firebase in VueJS

After a successful sign-in through Firebase authentication, I need to update a navigation link. The user login changes are managed within the created hook using .onAuthStateChanged() data () { return { user: null, additionaluserinfo: nul ...

What could be causing my Express API registration route to fail when attempting to POST?

Currently, I'm in the process of developing a compact authentication system for a practice project that I've undertaken. As part of this endeavor, I am sending POST requests via Postman to my Express server located at http://localhost:4000/api/re ...

Issue: Database not updating after input via AJAXExplanation: Despite submitting new data through AJAX, the

I've been struggling to display the UPDATED database on my initial html page after submitting new information. Despite successfully updating the database using AJAX, I can only see the outdated version. Any assistance in resolving this issue would be ...

What is the best way to populate an array with unique values while applying a condition based on the objects' properties?

Looking to create a unique exam experience for each student? I have an array of question objects and the goal is to select random and distinct questions from this array until the total sum of scores equals the specified exam score. This means that every s ...

Press a button to link a click event handler to another button

function example() {console.log('example');} $('#button1').click(function(){ $('#button2').onclick = example(); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> ...

Indicate the node middleware without relying on the port number

My website is hosted at mywebsite.com and I am using node and express for middleware services, pointing to mysite.com:3011/api. The website is hosted statically on Ubuntu 16 (Linux) and the middleware is run separately using pm2 (node server). I want to b ...

JavaScript regular expression for detecting valid characters without repeating a specific character

let rx = /(\/MxML\/[a-z0-9\[\]@/]*)/gi; let s = 'If (/MxML/trades[1]/value== 1 then /MxML/trades[type=2]/value must be /MxML/stream/pre/reference@href'; let m; let res = []; while ((m = rx.exec(s))) { res.push(m[1]); ...

What is the best way to prevent a folder from being included in the next js build process while still allowing

I am faced with a challenge involving a collection of JSON files in a folder. I need to prevent this folder from being included in the build process as it would inflate the size of the build. However, I still require access to the data stored in these file ...

Problem with character encoding in Node.js

I am encountering an issue while retrieving data from a request, as the formatting or encoding is not matching my requirements. Attempted to address this by setting the encoding with req.setEncoding('utf8') The expected string should appear as: ...

Unable to retrieve the ZIP archive generated dynamically

I am facing an issue while attempting to generate a dynamic output from MySQL queries and create an archive. Below is the code snippet I have been working with: var async = require("async"); var mysql = require("mysql"); var express = require("express"); ...

A method to efficiently send multiple axios GET requests by incrementing the URL parameters

Is there a way to efficiently send multiple HTTP GET requests using Axios? For instance: let maxRequests = 3000; let currentRequest = 0; do { currentRequest = currentRequest + 1; await response = axios.get(`https://example.com/${currentRequest}` ...

When using Selenium to locate an element, it appears to be returning an unexpected empty object

This question has been bothering me for quite some time. I am currently using Selenium in conjunction with Python to find an element within a webpage. The specific element I am targeting is as follows: <a id="topmenu_adhocQtraditional_Reports" ...

Tips for locating the existence of an Azure File in NodeJS

Currently, my project involves utilizing azure file storage along with express JS for creating a backend to display the contents stored in the azure file storage. The code I am working on is referencing this documentation: https://learn.microsoft.com/en-u ...

When using res.render to pass data to an EJS file and accessing it in plain JavaScript

I'm currently working on an Express GET function where I am sending data to an EJS file using the res.render() function. My question is, how can I access this data in plain JavaScript within the same EJS file? Here is my GET Function: router.get(&a ...

Is it possible for React Server Side rendering to be re-rendered on the client side?

In this demonstration of isomorphic rendering found at https://github.com/DavidWells/isomorphic-react-example, the author showcases Server Side Rendering by disabling Javascript. However, if JavaScript is enabled on the frontend, does it trigger a re-rende ...

Using Two JavaScript Functions with Identical Names in One HTML File

I am currently facing an issue with a function where the data is retrieved from the getValue() function. The following code snippet is a fragment. grid.js function gridLoadComplete(){ var data = getValue(); } Take into account the following H ...

Vue ceased to refresh the state of a particular variable

After attempting to populate a table using an axios get request and then trying to implement a Vuetify version of the table without success, I reverted the changes. However, now I am facing an issue where the data is not showing up in my table. Here is a ...

Wait until the user submits the form before activating Angular validations, and do not display any validation messages if the user deletes text from a text box

I am looking to implement angular validations that are only triggered after the user clicks on submit. I want the validations to remain hidden if the user removes text from a textbox after submitting it. Here is what I need: - Validations should not be dis ...

Get the docx file as a blob

When sending a docx file from the backend using Express, the code looks like this: module.exports = (req, res) => { res.status(200).sendFile(__dirname+"/output.docx") } To download and save the file as a blob in Angular, the following code snippet i ...