Utilizing Async/Await in conjunction with Vuex dispatch functionality

I'm currently working on creating a loader for specific components within my application.

Here is the code snippet for one of my components:

        mounted() {
            this.loading = true;

            this.getProduct();
        },
        methods: {
            async getProduct() {
                await this.$store.dispatch('product/getProducts', 'bestseller');

                console.log(123);

                this.loading = false;
            }
        },

Vuex action:

getProducts({commit}, type) {
        axios.get(`/api/products/${type}`)
            .then(res => {
                let products = res.data;
                commit('SET_PRODUCTS', {products, type})
            }).catch(err => {
            console.log(err);
        })
    },

The issue lies in this line of code:

await this.$store.dispatch('product/getProducts', 'bestseller');

The expectation was that the code would pause at this line, wait for the data to be loaded from the AJAX call, and then set the loading status to false; however, that did not happen. The loading status is still set to false, and the console.log statement runs before the data is fully ready.

An attempt was made to move the async/await logic into the Vuex action, which resolved the issue. However, the exact difference between the two approaches remains unclear.

Below is the updated code that successfully addressed the problem:

Component:

mounted() {
            this.loading = true;

            this.$store.dispatch('product/getProducts', 'bestseller').then((res) => {
                this.loading = false;
            });
        },

Vuex action:

async getProducts({commit}, type) {
        let res = await axios.get(`/api/products/${type}`);

        commit('SET_PRODUCTS', {products: res.data, type});
    }

Answer №1

Revise this section:

getProducts({commit}, type) {
    axios.get(`/api/products/${type}`)
        .then(res => {
            let products = res.data;
            commit('SET_PRODUCTS', {products, type})
        }).catch(err => {
        console.log(err);
    })
},

To the following:

getProducts({commit}, type) {
    return axios.get(`/api/products/${type}`)
        .then(res => {
            let products = res.data;
            commit('SET_PRODUCTS', {products, type})
        }).catch(err => {
        console.log(err);
    })
},

This adjustment should function as intended.

The axios.get method returns a promise. To properly utilize await, you must return this promise to ensure it can be awaited. Otherwise, returning implicitly as undefined will cause await undefined to resolve immediately.

Answer №2

Attempting to call a function without a promise is not possible

await this.$store.dispatch('product/getProducts', 'bestseller');

The aforementioned function either retrieves data or triggers another action

getProducts({commit}, type) {
    axios.get(`/api/products/${type}`)
        .then(res => {
            let products = res.data;
            commit('SET_PRODUCTS', {products, type})
        }).catch(err => {
        console.log(err);
    })
},

This function returns a promise due to its asynchronous nature

async function return promise

async getProducts({commit}, type) {
    let res = await axios.get(`/api/products/${type}`);

    commit('SET_PRODUCTS', {products: res.data, type});

}

By utilizing the above function, you can now execute

await this.$store.dispatch('product/getProducts', 'bestseller');

using the await keyword Alternatively, you can also return axios as it also provides a promise.

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

The use of a Bootstrap row is leading to incorrect dimensions for FullPageJS

Within the body tag, I have included the following code snippet: <div id="container"> <div class="section profile"> <div class="row"> <div class="col-sm-6"> A </div> ...

Is there a way to share the Username and Password without the need to manually input it?

My goal is to develop a C++ application for my classmates at school. Currently, they are required to visit our school's website and navigate to the login page. Once there, they enter their username and password, log in, and proceed to find their spec ...

React error: "Unable to locate property 'bind' within the undefined"

After reviewing several solutions, I'm still struggling to understand. Below is my code snippet: // userInputActions.js ... export function dummy() { console.log('dummy function called'); } ... // *userInputPage.js* import * as use ...

Setting up dynamic routing in AngularJS for links

I am facing some confusion regarding routing in AngularJS. Normally, we can configure routes in angular.config() when the angular module is loaded. At that time, we define static information such as routePath, templateUrl, and controller. However, I am u ...

Leverage ajax/js to dynamically refresh a single select tag within a set of multiple

While working on a project, I encountered a challenge while using JavaScript to update a <select> tag within a page. The specific issue arises because the page is designed in a management style with multiple forms generated dynamically through PHP ba ...

The JSX snippet accurately displays the expected value on some pages, but displays an incorrect value on other pages

{_id === friendId || <IconButton onClick={() => patchFriend() } sx={{ backgroundColor: primaryLight, p: "0.6rem" }} > {isFriend ? ( <PersonRemoveOutlined sx={{ color: primaryDark }} /> ...

Transmitting PHP variable to JavaScript using Callback Method

I am looking to implement password validation using JavaScript along with an Ajax function. Upon successful validation, I aim to return a boolean variable (true or false) and perform specific actions in my PHP file based on the callback. Unfortunately, my ...

The callback function for the XMLHttpRequest object is not triggered when making a cross-domain request using jQuery/Ajax

Looking for some help with this code snippet I have: $.ajax({ xhr: function() { var xhr = new window.XMLHttpRequest(); xhr.addEventListener("progress", function(evt) { if (evt.lengthComputable) { var percentCo ...

The perplexing phenomena of Ajax jQuery errors

Hey there! I'm having a bit of trouble with ajax jquery and could use some guidance. $.ajax({ type:"get", url:"www.google.com", success: function(html) { alert("success"); }, error : function(request,status,error) { alert(st ...

Express Angular Node Template Render throwing an error: module 'html' not found

I am currently in the process of creating a web application using AngularJS with ui-router for routing via $stateProvider, ensuring that only the specified states are displayed in the ui-view. In my server.js file, I have set up an initial framework such ...

Tips on eliminating overlapping strokes

I'm having trouble with drawing an array of circles that are meant to intersect a series of lines. The issue I face is that if the circles overlap, a stroke appears underneath them which I want to remove. Does anyone have any suggestions on how to el ...

Eliminate any blank spaces in the string before comparing the option value to determine whether the DIV should be

I am trying to create a function that hides or shows a specific DIV based on the option value selected from the product. Due to automatic addition of option values by Shopify, some options have more than one word with spaces in between. Since I cannot chan ...

Enhancing the visual appeal of a standard jQuery slider with thumbnails

Recently, I incorporated the Basic jQuery slider into my website, which can be found at . As a novice in jQuery but well-versed in HTML and CSS, I have managed to make it work seamlessly on my site. However, I am curious to know if there is a way to displa ...

Retrieve events triggered by each element

Currently, my research centers around digital marketing and user experience. In order to gather the necessary data for this study, I must collect event logs from all components within a UI to create datasets on usability patterns. In a web interface, such ...

Expanding the functionality of a regular expression

My goal is to identify JavaScript files located within the /static/js directory that have a query string parameter at the end, denoted by ?v=xxxx, where 'x' can be any character or number. Here's an example of a match: http://127.0.0.1:8888 ...

Unable to get jQuery click and hide functions to function properly

Hello, I am currently working on a program where clicking a specific div should hide its own class and display another one. However, the code does not seem to be functioning correctly. Below is my current implementation: $("#one").click(function(){ v ...

Is there a way to utilize JavaScript in order to trigger a CSS animation to occur at a designated time during a video

I have a cool animated image element that I want to play at a specific point in time during a video using JavaScript. I'm not sure how to make it happen, but I know the .currentTime property could be the key. My goal is for the animation to only play ...

Combine several items to form a single entity

When I have two objects returned from the database, my goal is to combine them into one object. Here are the examples: { "id": 4, "first_name": "s", "last_name": "a", ...

Why does my page keep refreshing even after I close the model?

I am facing the following issues: 1- Whenever I try to close my model by clicking 'cancel', it causes the page to reload. 2- Clicking 'OK' does not send the 'DELETE' request to the server, nothing is received, and the page r ...

Leverage JQuery Mobile for smooth sliding and effortless deletion of list elements

Currently, I am testing a JQuery Mobile webpage that features a simple list setup: Upon clicking the list items, they get highlighted and their ids are saved in a local array. Is there an easy (or not so easy) way to transition the selected elements slidi ...