Have you ever encountered issues with Promises.all not functioning properly within your vuex store?

I'm currently experiencing an unusual problem. In my Vue project, I have a Vuex store that is divided into different modules. I am trying to utilize Promise.all() to simultaneously execute two independent async Vuex actions in order to benefit from the first fail behavior.

store/modules/categories:

    async CATEGORIES({ rootState }) {
        const response = await axios.post('link_to_api', {
            // some arguments for the api
            arg: rootState.args
        })

        return response
    }

store/modules/transportation:

    async TRANSPORTATION({ rootState }) {
         const response = await axios.post('link_to_api', {
            // some arguments for the api
            arg: rootState.args
        })

        return response
    }

Now, I want to invoke those async functions within Promise.all:

store/modules/categories:

    async PUT_CATEGORIES({ commit, dispatch, rootState }) {
      try {
         const [resCategories, resTransportation] = await Promise.all([
            dispatch('CATEGORIES').catch(err => { console.log('Error fetching categories!'); throw {error: err, origin: 'categories'}; }),
            dispatch('transportation/TRANSPORTATION', {root:true}).catch(err => { console.log('Error fetching transportation!'); throw {error: err, origin: 'transportation'}; })
        ]) 
         //do something after both promises resolved

      } catch(error) {
            // do something if one promise rejected
            commit('errorlog/ERROR', 4, {root:true})
            dispatch("errorlog/LOG_ERROR", {'origin': '2', 'error_code': '113', 'message': error.toString()}, {root:true})
            router.push({path: '/Error'})
        }  

I encountered the following error:

https://i.stack.imgur.com/2ysmx.png

This is strange because I used {root:true} and the prefix transport in dispatch to access the action of the transport module in the store. This method works perfectly for the LOG_ERROR action in the errorlog module that I use in the catch block.

If I duplicate the TRANSPORTATION action in the categories module, it works fine...

Has anyone else encountered this issue before and can offer any advice??

Thank you in advance!

Answer №1

Your current code is passing {root:true} as the second argument when it should actually be passed as the third argument.

- dispatch('transportation/TRANSPORTATION', {root:true})
+ dispatch('transportation/TRANSPORTATION', null, {root:true})

Referencing Vuex's documentation:

To perform actions or mutations in the global namespace, include { root: true } as the 3rd argument when dispatching and committing.

They provide a simplified example code snippet:

modules: {
  foo: {
    namespaced: true,
    actions: {
      // Dispatch and commit are scoped for this module
      // Use `root` option for global dispatch/commit
      someAction ({ dispatch, commit, getters, rootGetters }) {
        dispatch('someOtherAction') // -> 'foo/someOtherAction'
        dispatch('someOtherAction', null, { root: true }) // -> 'someOtherAction'

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

Firefox throwing an error with jQuery URL Get requests

Could someone help me understand why my JavaScript function is triggering the error function instead of the success function in Firefox on Ubuntu? $(document).ready(function() { console.log( "Begin" ); $.ajax({ type: "GET", dataType: "ht ...

Invoking a function beyond the boundaries of an Angular application

The Angular code I have is structured within a single module and controller. app.controller('MainCtrl', function($rootScope, $http) { $rootScope.graph = {'width': '100%', 'height': 500}; $rootScope.rectangl ...

Ways to enhance the type definitions for a built-in HTML element in Vue.js?

Imagine having an element that wraps around an input and inherits all of its properties, along with some extras. In React, you would define this as: interface ExtendedInputProps extends React.ComponentPropsWithoutRef<'input'> { some: T ...

Using Angular to make an API call within a JavaScript function

I am facing an issue when trying to call an API in a JavaScript function as shown below. The injected services (subService) and defined variables (formData) are not recognized in the JavaScript function, resulting in an error of undefined addSub. How can I ...

What is the process for adjusting the input value dynamically in reactjs?

I am working on a dynamic time input row and I need to ensure that the values are updated correctly. This is the code snippet I am using: https://codesandbox.io/s/624vq8y7y3 When I run the code, the values in the TimeInput field do not change as expected ...

The Transparent Quirk in Three.js

Hey there! I'm working on displaying a 3D avatar on my website that allows users to apply textures to the character. I'm hoping to enable users to create transparent textures so they can see the model underneath. Right now, when implementing tran ...

Ways to split a string using jQuery

I am working with a jQuery string array that contains the following elements: ["$1#Structure$2#Accounting$3Acc#$1Programming"] My task is to split the strings after the '#' symbol and provide the following result: ["Structure","Accounting","Ac ...

The error message "Then is not defined in Element UI Plus" is throwing a ReferenceError

I am currently utilizing the vue3 framework along with element-ui-plus for a project I am working on. However, when attempting to use the MessageBox feature within element-ui-plus, an error Uncaught ReferenceError: then is not defined occurred. All other ...

The property cannot be set because it is undefined in nodejs

var list = [ { title : '', author : '', content : '', } ] router.get('/japan',function(req,res){ var sql = 'select * from japan'; conn.query(sql,function(err,rows,fields){ for(var i = 0 ; ...

What is the technique for defining sub paths in React-Router-Dom by excluding the parent path?

Imagine a Profile page that displays different components based on the path it receives. For example: /profile/posts will show the Posts component within Profile. /profile/comments will display the Comments component inside Profile. Typically, the Profi ...

Adjusting the speed of Vuetify transitions: A guide on setting the perfect transition speed

Looking to have an audio player component smoothly slide up from the bottom of its parent component? You can nest it within a <v-slide-y-transition> Vuetify component, but how can you control the speed of the sliding animation? <v-parallax src= ...

While executing a for loop, the variable $.ajax is found to be null in Javascript

When I click on a button with the function btn-book, there is a for loop inside it that fetches data from Ajax. Despite knowing that the data holds values, I constantly receive null. Below is the code snippet for the onclick event: $('#mapContainer&a ...

Serve static files using ExpressJS when a post request is made

My Express server is set up to serve static files for my website and it's working fine: var express = require('express'); var app = express(); var path = require('path'); var p = path.join(__dirname, '../web/public'); app ...

In order to preserve the data inputted by the user within a file

Check out this HTML code snippet:- ` AngularJS | $http server <div ng-controller="people"> <ul> <h2> Names and Ages of programmers: </h2> <li ng-repeat="person in persons"> { ...

JavaScript is displaying Not a Number (NaN) instead of the expected value

Currently, I am facing an issue with retrieving the user's work duration from a database column stored in minutes. My goal is to convert this value to HH:mm format to calculate the total hours worked per week, but I'm encountering obstacles. < ...

`Nextjs customizes the position of locales`

Currently implementing i18n translation in my project, the default root appears as follows: https://example.com/en/business/transaction Is it possible to customize the root to appear as: https://example.com/business/en/transacation Thank you. ...

Using @carbon/react in conjunction with Next.js version 13 leads to unconventional styling

Here's what I did to set up my Next.js application: npx create-next-app@latest I then installed the necessary package using: npm i -S @carbon/react The global styles in app/globals.scss were customized with this code snippet: @use '@carbon/reac ...

Store the checkbox's data in the database for safekeeping

Hey there, I'm working on saving the value of a checkbox using PHP. The twist is that the value is generated through JavaScript. How can I handle this scenario and save the value using PHP? Checkbox: <input type='checkbox' name='ca ...

Identifying the various types in Typescript

In the process of developing a solution for Excel involving data from an Office API, I encountered the challenge of distinguishing between different types that a function can return. Specifically, the data retrieved as a string may belong to either a "Cell ...

Working with jQuery.ajax Function Calls in Array Filter Operations with Javascript

My knowledge of AJAX calls is limited, so I am unsure about how they interact with array filtering using A.filter(). The array in question is used to populate a template synchronously. // An event triggers a function to filter a list on the page. // The f ...