Is there a way for me to receive the response from the this.$store.dispatch method in vue.js 2?

Here is the structure of my component :

<script>
    export default{
        props:['search','category','shop'],
        ...

        methods: {
            getVueItems: function(page) {
                this.$store.dispatch('getProducts', {q:this.search, cat:this.category, shop: this.shop, page:page}).then(response => {
                    console.log(response)
                    this.$set(this, 'items', response.body.data)
                    this.$set(this, 'pagination', response.body)
                }, error => {
                    console.error("this is error")
                })
            },
            ...
        }
    }
</script>

The ajax call for the getProducts method is in the product.js module

The product.js module code is as follows :

import { set } from 'vue'
import product from '../../api/product'
import * as types from '../mutation-types'

// initial state
const state = {
    list: {}
}

// actions
const actions = {
    getProducts ({ commit,state }, payload)
    {
        product.getProducts( payload,
            data => {
                let products = data
                commit(types.GET_PRODUCTS,{ products });
            },
            errors => {
                console.log('error loading products ')
            }
        )
    }
}

// mutations
const mutations = {
    [types.GET_PRODUCTS] (state, { products }) {
        state.list = {}
        products.data.forEach(message => {
            set(state.list, message.id, message)
        })
    }
}

export default {
    state,
    actions,
    mutations
}

The getProducts method is then called in the product.js API module

The product.js API code looks like this :

import Vue from 'vue'
import Resource from 'vue-resource'

Vue.use(Resource)

export default {
    // api to get filtered products
    getProducts (filter, cb, ecb = null ) {
        Vue.http.post(window.Laravel.baseUrl+'/search-result',filter)
            .then(
            (resp) => cb(resp.data),
            (resp) => ecb(resp.data)
        );
    }
}

After execution, I found that the response does not show up and it's undefined

How can I resolve this issue?

UPDATE

If I use a normal ajax call like this :

<script>
    export default{
        props:['search','category','shop'],
        ...

        methods: {
            getVueItems: function(page) {
                const q = this.search
                const cat = this.category
                const shop = this.shop
                this.$http.get('search-result?page='+page+'&q='+q+'&cat='+cat+'&shop'+shop).then((response) => {
                    console.log(JSON.stringify(response))
                    this.$set(this, 'items', response.body.data)
                    this.$set(this, 'pagination', response.body)
                });
            },
            ...
        }
    }
</script>

This approach works and successfully retrieves the response

However, why does it not work when using Vuex store?

Answer №1

In order to properly handle asynchronous actions in your application, it is important to make sure you are returning a Promise within your actions.

Here's an example:

// actions
const actions = {
    fetchUserData({ commit, state }, payload) {
        return new Promise((resolve, reject) => {
            api.fetchUserData(payload)
                .then(data => {
                    let userData = data;
                    commit(types.FETCH_USER_DATA, {userData});
                    resolve(data);
                })
                .catch(error => {
                    console.log('An error occurred while fetching user data');
                    reject(error);
                });
        });
    }
}

Another option is to simply use return Vue.http.post() directly within your action.

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

Submitting the Ajax form will result in the quantity of the product in the cart being updated while remaining on

Hello, I am using ajax to keep the user on the same page after submitting a form. If successful, I will use ajax load to load another page that displays the quantity of the product. However, I am facing an issue where each subsequent submit increases the q ...

Beginning the deployment of a Nuxt SSR application on Azure with the build files

According to the Nuxt documentation, running yarn build will result in Nuxt.js creating a .nuxt directory containing everything ready for deployment on your server hosting. After reviewing a couple of other guides, it appears that additional items require ...

Validating usernames using Jquery's remote method检verifying the username

Struggling with the validation plugin and Laravel 4.2. I've been attempting to use ajax to check the username, but it's not functioning as expected. No matter if the username exists or not, it always appears available. Another problem arises whe ...

Encountering a NaN outcome when summing values from various select options

I'm working on a project that involves adding up the prices based on the surface chosen by the user. I'm struggling with calculating the partial cost when the user's choice changes. totalSum.ts num: Calculation totalAmount: number cate ...

Utilizing Bootstrap CSS within Vue's scope

I'm attempting to integrate Bootstrap into a Vue component while ensuring that all CSS is scoped. My initial approach was as follows: <style scoped> @import "~bootstrap/dist/css/bootstrap.css"; @import "~bootstrap-vue/dist/bootstrap-vue.css"; & ...

Problems with the Chosen property of MenuItem within Material-UI

The MenuItem's "selected" property does not seem to be functioning correctly within the Select component. For reference, please visit https://codesandbox.io/s/9j8z661lny I have attempted to use comparison with the Id, and even tried using selected={t ...

Is there a Node.js method that is similar to jQuery AJAX's .complete() function

In the process of creating a Node.js API to enroll a user in a different web application, I encountered an issue. As part of the registration flow, the API called by the Node app using request is being redirected with a status code of 301 to another API to ...

Trying to showcase information received from a server using an API

For a school project, I am developing a website that can retrieve weather data (currently just temperature) based on a city or zip code from openweathermap.org using an asynchronous call. I have successfully retrieved the data from the API, but I am strug ...

Tips for removing duplicate objects from an array

I am utilizing the underscore.js plugin in my code I experimented with it on jsfiddle var basket=[{ "basketitems":[{"items":[]}], "itemdetails":[{ "amountPledged": "100", "bActivity": "Handloom Wo ...

Express Node.js Error: Address Information Syntax Issue

While developing my server using TypeScript for my Angular app to connect to, I encountered an issue when trying to run the code snippet below. It seems that Node.js or TS is not yet compatible with certain ES6 features like destructuring with AddressInfo, ...

Guide on deactivating a button when a numerical value is detected within a field in VUE JS

I need help figuring out how to automatically disable a button when a field contains a number. Here is an example of my code: disabledSubmitButton() { return this.$v.$error || this.firstName === '' || this.lastName === '' || ...

Japanese Character File Naming Convention

When dealing with certain Japanese characters, the content disposition header appears as follows: Content-Disposition: attachment; filename=CSV_____1-___.csv; filename*=UTF-8''CSV%E3%82%A8%E3%83%93%E3%83%87%E3%83%B3%E3%82%B91-%E3%82%B3%E3%83%94%E ...

How to create a calendar selection input using PHP?

Before I start writing the code myself, I am searching to see if there is already a solution available or if someone has previously outsourced the code. Below is an example of my date selection: I want to create a feature where selecting a month will aut ...

Handling CORS in Vue.js applications

As a newcomer to Vue, I am currently grappling with a CORS issue in my application. During development at http://localhost:8080/, sending a request to , I was able to resolve the CORS problem using the following code snippet: vue.config.js module.exports ...

Article: Offering CoffeeScript and JavaScript Assets Simultaneously

Currently, my web app is up and running using Node and Express. I initially developed it in JavaScript but now want to transition over to CoffeeScript. My goal is to have both file1.js and file2.coffee coexisting in the application (with both being served ...

There seems to be an issue with Jquery not triggering the Webservice method in the Firefox browser, despite it working successfully in Chrome

Currently, I have an issue where a webservice method called via ajax in jQuery is functioning correctly in Chrome and IE browsers but not in Firefox. Here is the jQuery code: $("#btnUpdate").click(function () { var objEmp = { employeeID: $("#Em ...

What is the method for altering the color of specific columns?

I am currently testing out my Amchart with this example. Check out the working demo on code pen My goal is to modify the color of the first four columns. While I am aware that colors can be changed by specifying them in the JSON file as a property calle ...

What sets apart these two JavaScript namespaces?

My main goal is to expertly organize my javascript code by eliminating any global elements. I came across two namespace declaration methods in this informative post, and now I'm looking for your input on the advantages and disadvantages of each. ...

Novice in AngularJS routing

Having trouble with my first AngularJS routing code. The error console isn't much help. Here is my HTML page: <body ng-app="myApp"> <div ng-controller="AppController"> <div class="nav"> <ul> <li> ...

What steps can be taken to ensure express Node.JS replies to a request efficiently during periods of high workload

I am currently developing a Node.js web processor that takes approximately 1 minute to process. I make a POST request to my server and then retrieve the status using a GET request. Here is a simplified version of my code: // Setting up Express const app = ...