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

Unleashing the power of async/await in React: A comprehensive guide

Looking to simplify my code, I am interested in implementing async and await for the following code snippet. However, I am unsure of how to proceed. Any examples would be greatly appreciated. deletePost = (post) => { var post_id = post; try { ...

What is the appropriate way to utilize `render_template` from Flask within Angular?

I'm facing an issue where I need to implement different routes for various Angular Material tabs. I have attempted to directly call Flask from the template, as demonstrated below, but unfortunately, I am unable to invoke render_template from Angular. ...

Combining the elements within an array of integers

Can anyone provide insight on how to sum the contents of an integer array using a for loop? I seem to be stuck with my current logic. Below is the code I've been working on: <p id='para'></p> var someArray = [1,2,3,4,5]; funct ...

PHP and MySQL combination for efficient removal of multiple dropdown choices

I'm struggling to figure this out. Essentially, it's a form with multiple dropdown menus where users can select one or more items to filter MySQL data results. I want to dynamically update the other dropdown menus as the user makes selections. Fo ...

Is it necessary to re-export a module after modifying an attribute in it in JS/ES6?

From my understanding of the module system, when I use import 'some_module' in a file, I will always receive the same instance of that module and not a new instance each time. However, I am a bit puzzled by a pattern I have observed in certain a ...

I am having trouble with node.js express not recognizing the path to my CSS files

My objective is to load information onto an HTML page using Node.js and Express. The issue I am facing is that when I try to open the main page (which displays all the books from the database), everything works smoothly - the CSS and JS files are located ...

"Encountered issues during compiling: X ERROR found at line 9 in the Header.js file, spanning from characters

An error occurred while compiling the module. The following message was displayed: Module not found: Error: Can't resolve '@mui/icons-material/Search' in 'C:\Users\pande\Documents\slack-clone\src\component ...

Exploring the world of WebSockets and Socket.io

Recently many online games, like , have started using WebSockets to create real-time MMORPGs. I'm curious about how to develop a node.js program that can manage connections from browsers using WebSockets. Here is an example of browser code: <!DOC ...

Trigger a function following a collection update in Angular Meteor

I am in the process of developing a multiplayer game, and I would like a specific function to be triggered once the first player updates an "isStarted" field in the collection. Within my controller code: angular.module('mcitygame').directive(&a ...

The website is experiencing functionality issues with Ajax

On my personal website, I am trying to add a simple ajax server clock in the header section but unfortunately it is not appearing as expected. Here's the snippet of Javascript code that I am using: var httpxml; try { // Firefox, Opera 8.0+, Safari ...

Is it acceptable to compare a boolean with a string?

In my code, I have a variable called isRefreshed which is initially declared like this: var isRefreshed = ''; Sometimes, in certain scenarios, isRefreshed can be assigned a boolean value, for example: isRefreshed = false; Now, there is an if ...

Where is the function returned by redux-thunk invoked?

Can you help me understand where the function returned by addUser is being called in this action creator and redux thunk function? const userAdded = () => ({ type: types.ADD_USER, }); export const addUser = (user) => { return function (dispat ...

Javascript code to verify whether the page is currently positioned at the top

How can I use JavaScript to determine if the page is at scroll(0,0)? I have a full-page slider that needs to pause when the page is no longer at the top. The page may not be scrolled manually, as there are internal HTML # links that could load the page d ...

modifying the href attribute of a tag is determined by the value of window

I'm working on a jQuery snippet that detects the current window's URL and, depending on the href value of the window, changes the href of an anchor tag. Here's what my code looks like so far: (function($) { "use strict"; $(document).re ...

Switching from PHP to JavaScript before returning to PHP to establish and manage sessions

Currently, I am in the process of resolving an issue I am facing. The problem arises when utilizing the following code for someone trying to sign into the admin panel: <script> function myFunction() { //alert('you can type now, end ...

How can you create an event that is focused on options using Material-UI's Autocomplete feature?

This is regarding Material-UI's Autocomplete feature. I am looking for a way to track which autocomplete choice the user is currently focused on, whether it be through hovering over with the mouse or using keyboard arrows - before any actual selection ...

Exploring the bewilderment of retrieving values in a JavaScript

I'm confused about the return value of this code snippet: function foo() var ret = 0; var xhr=send_request( "bla", function() { // perform actions based on AJAX response // set the value of ret based on the response } ); return re ...

Attempting to store the output of a function in a variable

My current script is designed to verify if the value of a selected element matches the span id. While the function itself functions correctly (verifying object.id via alert), I am encountering issues with variable assignment. When attempting to alert the ...

Troubleshooting issue with C# Ajax success response not triggering alert

I am facing an issue where the alert box for success does not show even though the code successfully inserts contact details using ajax and C#. Strangely, when I debug through the JavaScript debugger in Chrome, the alert pops up as expected. Here is the co ...

Clearing a textarea in jQuery that is populated with text

Having an interesting dilemma. I'm trying to clear a <textarea> and then replace it with new content. The functions in the JSFiddle will work perfectly fine if the textarea is left empty, but as soon as any text is manually typed into it, the me ...