Can Vuex mapActions be utilized within a module that is exported?

Is it possible to utilize Vuex mapActions from an external module imported into a component?

I am working on standardizing a set of functions in a vue.js web application. My goal is to import these functions into each component and pass necessary values for them to operate. I am using Vuex for state management. Currently, each component independently calls these functions when loaded, duplicating the process.

I aim to refactor this by consolidating all functions into one module and importing it into the components as needed. This module utilizes mapActions as part of its functionality. Below are snippets of code: Vue component, module script, and Vuex action:

Vue component:

// Calling the imported function
if (!this.queued){
   timer.updatePage(this.pagination, this.orders);
}

Module script (advance.js):

import { mapActions } from 'vuex';

let currentComp = {
   name: 'purchase',
   date: null,
   start: false
}

const timer = {
   ...mapActions(['currentComponent']),
   updatePage(pagination, order) {
      currentComp.name = 'nextComponent';
      this.currentComponent(currentComp);
   }
}
export default timer;

Vuex action code:

// Within the actions section:
currentComponent({
        commit
    }, comp) {
        console.log(comp);
        commit('setCurrentComponent', comp);
}

// Within the mutations section:
setCurrentComponent: (state, comp) => {
        state.currentComponent = comp.name;
        return state;
    }

When running the component with the imported function, an error occurs:

vuex.esm.js?2f62:870 Uncaught TypeError: Cannot read property 'dispatch' of undefined
    at Object.mappedAction [as currentComponent] (vuex.esm.js?2f62:870)
    at eval (advance.js?935c:37)

Removing 'this' from 'this.currentComponent' results in another error:

advance.js?935c:37 Uncaught ReferenceError: currentComponent is not defined
    at eval (advance.js?935c:37)

Thanks in advance for any advice or pointers.

Answer №1

mapActions provides a shortcut for generating a method that resembles the following:

currentComponent() {
   this.$store.dispatch('xxx')
}

When executing this method, the context of this is set to timer. However, since timer does not possess a $store property, it results in the error message "

Cannot read property 'dispatch' of undefined
". To rectify this issue swiftly, you can change the context of this to the component that actually owns the $store property. This can be achieved by passing the component as a third parameter in the updatePage function and binding currentComponent accordingly.

// component code
timer.updatePage(this.pagination, this.orders, this);

// advance.js
const timer = {
   ...mapActions(['currentComponent']),
   updatePage(pagination, order, component) {
      currentComp.name = 'nextComponent';
      this.currentComponent.bind(component)(currentComp);
   }
}

It is advisable to utilize a mixin for handling this scenario more effectively.

import { mapActions } from 'vuex';

let currentComp = {
   name: 'purchase',
   date: null,
   start: false
}

const timerMixin = {
   methods: {
       ...mapActions(['currentComponent']),
       updatePage(pagination, order) {
          currentComp.name = 'nextComponent';
          this.currentComponent(currentComp);
       }
   }
}
export default timerMixin;

Within your component, import the timerMixin and incorporate it as a mixin. Subsequently, these methods will be directly accessible within your component and can be invoked with a slight adjustment to your existing code.

if (!this.queued){
   this.updatePage(this.pagination, this.orders);
}

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

What is the best method for deleting a portion of a string following the final instance of a particular character?

I have a single string that looks like this: "Opportunity >> Source = Email >> Status = New >> Branch = Mumbai" My goal is to truncate the string from the last occurrence of >>. Essentially, I want the resulting string to be: "Op ...

WebStorm not recognizing NodeJS Core Modules in External Libraries

As a newcomer to NodeJS and WebStorm, I am currently diving into a tutorial on creating an Express app. In the tutorial, the instructor always gets prompted with "Configure NodeJS Core Module Sources" including the URL nodeJS.org when creating a new NodeJ ...

Tips for maintaining JSON data in CK Editor

I'm having an issue where my JSON data is not being displayed in CKEditor when using this code function retrieveRules(){ $.ajax({ url: "api", type: "POST", data: { version:'0.1' }, ...

I'm experiencing an issue with fullCalendar where the dayRender function is not functioning as expected

I have been using fullCalendar and I am looking to customize the color of specific days. I have successfully created an overlay that is displayed when a user clicks on a particular day. Everything works as expected with the overlay, but now I am encounte ...

Learning how to interpret input from the command line in Vertx

Would appreciate some guidance on how to read command line arguments in vert.x using JavaScript. For instance, I am wondering how to go about reading: arguments(arg1, arg2, arg3) vertx run example.js arg1 arg2 arg3 ...

When using $state.go in $stateChangeStart, there is a dual state transition in ui-router

Take a look at my Plunker. When you click on the profile link and examine the list of state changes: stateChanges = [ " -> home", "home -> profile", "home -> signIn", "signIn -> signIn" ] You'll notice an unexpected extra state c ...

Achieve the appearance of a galloping horse using JQuery

I am looking for a way to create the illusion of a horse running by displaying a sequence of images quickly. Each image in my folder shows the horse in motion, and I want to make it appear as if the horse is actually moving. Can anyone recommend a librar ...

Transform input string containing newline characters into separate paragraphs

I utilize Contentful CMS for content management and fetch the content through their API. When the content is fetched, it comes in as a JSON object. One of the keys within this object pertains to the main text block for the entry I am retrieving. This stri ...

Establish a connection to an already existing database using Mongoose

I've been exploring the inner workings of MongoDB lately. After setting up a local database, I created a collection with the following document: db.user.find().pretty() { "_id" : ObjectId("5a05844833a9b3552ce5cfec"), " ...

Image not yet clicked on the first try

I am encountering an issue with my image gallery. Currently, when I click on a thumbnail, the large image is displayed. However, I would like the first image to show up without requiring the user to click on its thumbnail. How can I address this problem? B ...

The authentication callback function fails to execute within Auth0 Lock

I'm having an issue with logging into my application using Auth0. I have integrated Auth0 Lock version 10.3.0 through a CDN link in my project and am utilizing it as shown below: let options = { disableSignupAction: true, rememberLastLogin: f ...

Ensure to close the Ajax request from PHP before the script finishes executing

Is there a way to terminate an Ajax request from PHP before the script finishes executing? For instance, if a user requests php.php and it includes the line 'echo "phpphp"', how can we ensure that the Ajax request is completed with the data "phpp ...

Update the message displayed in the user interface after the view has been fully rendered in an Express application, following the execution of asynchronous

I have created a simple express app that reads files from a directory, renames them, zips the files asynchronously, and then renders another view. The file reading and renaming are done synchronously, while the zipping part is handled asynchronously. My cu ...

Ways to showcase the object on the console

How can I display the object function in the console? When I try, nothing is displayed. Can you please help me figure out what went wrong? I know I must have made a mistake somewhere, as this is my first question on Stack Overflow. import React, ...

Searching for a specific row of data by ID in a massive CSV file using Node.js

Can someone recommend an npm package that is ideal for iterating over a csv file, locating a specific value, and updating/appending to that particular row? I don't have any code to display at the moment as I'm in the process of testing different ...

What is the best way to update the state of a particular slider component?

When trying to update the value of a specific slider during the onChange event, I noticed that it was affecting all sliders instead. Is there a way to target and set the state of only one slider during this event? Here's what I've attempted so f ...

Unable to generate a fresh database entry through form submission

I have designed User and Pairings models as shown below: class User < ActiveRecord::Base enum role: [:student, :supervisor, :admin] has_many :students, class_name: "User", foreign_key: "supervisor_id" belongs_to :supervisor, ...

Emailer: Missing Salutation

While attempting to send emails using Node with Nodemailer (https://github.com/nodemailer/nodemailer), the sendMail call from the Nodemailer transporter is throwing an error message of Greeting never received when connected to an Ethereal test email accoun ...

Are Lazily Instantiated Singletons a Thing in AngularJS?

After browsing through the AngularJS documentation, I came across an interesting detail about AngularJS services: AngularJS lazily instantiates services, meaning they are only created when a component in the application requires it. Services in AngularJ ...

An async function cannot be used as a Constructor

I am in the process of creating a constructor function using JavaScript. This constructor needs to be asynchronous because I am utilizing the Phantom JS module for data scraping. As a result, an asynchronous function must be used to scrape data through Pha ...