Contrasting Vuex 2.0 Dispatch with Commit

When is it appropriate to utilize a dispatch instead of a commit?

From my understanding, a commit initiates a mutation while a dispatch triggers an action.

But can't we consider a dispatch as its own type of action as well?

Answer №1

Correctly stated, the $dispatch function triggers an action, while commit triggers a mutation. Here is how you can utilize these concepts:

Use $dispatch in your methods within routes/components to send a message to the vuex store for performing an action. This action can be executed at any time after the current tick to prevent frontend performance issues.

Avoid using commit directly in components/routes. It should only be used within an action and when there is data to commit. This is because commit is synchronous and could freeze the frontend until completed.

For instance, if you need to fetch JSON data from a server asynchronously to prevent UI unresponsiveness, simply trigger an action with $dispatch. The action will then handle fetching the data and updating the state accordingly.

If you require knowledge about when an action is complete to display an AJAX spinner, consider returning a Promise as demonstrated below (e.g., loading current user):

Define the "loadCurrentUser" action like this:

actions: {
    loadCurrentUser(context) {
        return new Promise((resolve, reject) => {
            this.$http.get("/api/current-user").then(response => {
                context.commit("saveCurrentUser", response.body)
                resolve()
            }, response => {
                reject()
            })
        })
    },
    // Additional actions
}

In the mutations handler, all commits originating from actions are managed. Define the "saveCurrentUser" commit as follows:

mutations: {
    saveCurrentUser(state, data) {
        Vue.set(state, "currentUser", data)
    },
    // More commit handlers (mutations)
}

In your component's created or mounted hook, call the action like this:

mounted: function() {
    this.$store.dispatch("loadCurrentUser").then(response => {
        console.log("Data received, now display content")
    }, error => {
        console.error("No data retrieved. Prompt user to check internet connection.")
    })
}

Optionally returning a Promise as described above is a design choice not favored by everyone. For a detailed discussion on whether to use Promises or not, refer to the comments under this answer:

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

"Utilize the Vue carousel's goToPage method to dynamically navigate to a specific page within

When using vue-carousel, I encountered an issue with passing a collection of locations and managing them across different parts of the page. To solve this problem, I emitted the selected location to the root via an eventHub where all locations and selected ...

The function n.blur is not a valid method in jQuery

I'm having issues with this code. The console is displaying an error that says n.blur is not a function. var username = '', elem = '', fullName = $('.form input[name="user"]'), emailAddress = $('.form in ...

Successful response from WordPress AJAX

I am currently working on setting up a contact form in WordPress using wp_mail along with Ajax. The email functionality is working fine, but I am facing some issues with the success response from Ajax. After sending the email, I want to display a message ...

Verification of input on ng-repeat table

I am working on an AngularJS app and have a table with ng-repeat where I have textboxes in td. I want to validate these textboxes so I tried using ng-form and ng-class, but I keep getting an invalid expression error. Here is my code: <input name ="abc ...

Unraveling the mysteries of JQGrid column sizing characteristics

My tree grid is causing me some headaches with its columns all having specified widths. The headers and columns below are completely out of sync, even when the data in them is short. In particular, when a column heading title is shorter than the width of ...

ways to display a chosen option in a dropdown menu

Below is the code snippet I am currently using, which involves JQuery and Bootstrap 4: $('.dropdown-menu li').on('click', function() { var selectedValue = $(this).text(); $('.dropdown-select').text(selectedValue); }); & ...

Implementing jQuery validation on tab key press

Is it possible to implement field validation in JSP while tabbing through the fields using jQuery? Here is a snippet of my JSP page: <form:form method="POST" commandName="test" name="testname" onclick="submitForm();" > <div> <form:inpu ...

Is it possible to display tooltips in amcharts based on specific conditions?

How can I display tooltip text in the chart based on a specific condition? I only want to show the tooltip text if the value is not equal to 0. Series.columns.template.tooltipText = `{valueY}s`; The tooltip currently displays the value of {valueY}, but I ...

Iterate using jQuery through all child div elements

<div id="SelectedSection" class="selected"> <div class="sec_ch" name="7"> <div class="sec_ch" name="8"> <div class="sec_ch" name="9"> <div class="sec_ch" name="11"> <div class="clear"> </div> </di ...

Generate a dynamic vertical line that glides smoothly over the webpage, gradually shifting from one end to the other within a set duration using javascript

I have designed a calendar timeline using html. My goal is to implement a vertical line that moves from left to right as time progresses, overlaying all other html elements. This functionality is similar to Google Calendar's way of indicating the curr ...

Tips on displaying a div next to an image icon using CSS and jQuery

I have a data table with an interesting feature - when you hover over the icon in the last column, it displays more information about that specific record. Here's how it looks: ORIGINAL VIEW However, I'd like to enhance this functionality by di ...

Implementing dynamic dropdown population in Angular 2 based on selection from another dropdown

I am relatively new to Angular 2 and currently facing a challenge in populating a dropdown menu based on the selection from another dropdown menu from MongoDB. The Issue: While I can successfully load the rooms, I encounter a problem when trying to load t ...

The request body is not defined within the Express controller

Currently facing an issue with my controller: when I use console.log(req), I can see all the content of the request body. However, when I try console.log(req.body), it returns as undefined. This problem arises while working on my Portfolio project with Nex ...

Unable to scroll when utilizing ng-html-bind functionality

My device specifications: $ ionic info Your system details: Cordova CLI: 6.2.0 Gulp version: CLI version 3.9.1 Gulp local: Ionic Framework Version: 1.2.4 Ionic CLI Version: 2.0.0 Ionic App Lib Version: 2.0.0-beta.20 OS: Distributor ID: LinuxMint Desc ...

Exploring portfinder in Javascript: A guide to its usage

As a newcomer to Javascript, I am eager to figure out how to utilize the portfinder.getPort() function within one of my functions in order to generate a random port each time. The code snippet below showcases my current implementation: var portfinder = re ...

Choosing multiple options from a list

I am working on a messaging app where users can compose and send messages to contacts. Currently, I am only able to send messages to one contact at a time. My goal is to enable users to select multiple contacts to create group messages. Since I am new to a ...

JavaScript variable not refreshing its value after submitting an HTML form

In my HTML form, I have 8 textboxes enclosed in div tags with IDs ranging from fa1 to fa8. By default, two of the textboxes are visible while the remaining six are hidden. To toggle the visibility of these divs, I've implemented two buttons - addfa an ...

Issue where the selected value from Semantic UI React dropdown fails to display after being chosen

I'm struggling to display the selected value from the dropdown inside the dropdown itself after it's been chosen. Even though the correct value is being set (verified through console logging), it doesn't show up in the actual dropdown. ...

Searching for elements in ASP.NET with Jquery

I need help with implementing validation for textboxes and dropdown lists using jQuery in a form that contains an AJAX Toolkit's tab container. The form includes a repeater displaying search results, where users can update data. I want to prevent the ...

How to access a custom filter in ng-repeat using AngularJS

I'm working on creating a filter to sort through the items displayed in a table. Specifically, I want to filter out items based on a certain property value that may change depending on user input. I have attempted the following approach and it seems t ...