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

Using the fetch method to consume a RapidAPI JSON response

Currently, I am in the process of learning React Native and have initiated a project for that purpose. In this project, I have integrated RapidAPI (link: ) to fetch necessary data. Upon hitting the API, I receive a 200OK status, but unfortunately, I am fa ...

VueJS Vuetify automatically centers default content

Vue cli version @ 5.0.6 | Vuetify version: [email protected] I have been utilizing Vue.js and Vuetify for some time now, and I can't shake the feeling that not all Vue.js/Vuetify components default to centered alignment. I recently initialized a ...

Animating computed values with VueJS transitions

I am looking to create an animated block of posts that can be filtered. When certain filters are applied, a computed method filteredPosts is triggered and assigned to a component like this: <block-article :posts="filteredPosts" /> Within my <blo ...

What steps should I take to fix the TypeScript Compiler issue "Global member 'NodeJS' has no exported namespace 'Global'?"

QUERY: What steps should I take to fix the Typescript Compiler (tsc) error stating "Namespace 'NodeJS' has no exported member 'Global'"? Upon executing tsc, this particular error unexpectedly appeared in a project that is considered "l ...

How to transform a nested string into a JSON object using JavaScript

I am trying to manipulate a nested query string in JavaScript. The string looks like this: var str = "( ( Sentence starts with any of null AND Sentence starts with any of null ) AND Sentence starts with any of null )" I want to split the string at the &a ...

having difficulty choosing a particular identifier from a JSON string

I'm currently working on a project to create an admin page for managing client information. However, I've encountered an issue where I am unable to select the client's unique ID to display all of their information on a separate page. On the ...

Execute the script when the document is fully loaded

Is there a way to show a dialog in jQuery when the document loads without using <body onload="showdialog();">? Can the javascript code be placed in the main div or footer div to work like the onload event? <body onload="$('#dialog').sli ...

What is the best way to get rid of trailing numbers in material UI class names?

The standard class for the material ui input box is .MuiInputBase-input, but when I inspect it using developer tools, I see that the same class is displayed as .MuiInputBase-input-619. How can I remove the suffix from the class name? I am currently utili ...

Fetch search results dynamically in Wordpress through AJAX

I'm struggling to implement AJAX on my WordPress site to display search results without refreshing the page. Despite trying various solutions found through research, none seem to be working effectively for me. Currently, here is the progress I have ma ...

Retrieve a file from a remote server without storing it locally on the server

I need to download a zip file from another server without saving it locally. Currently, I am sending a POST request to the server which responds with the zip file, then I save it on my local server and send it using res.download. What I would like is to di ...

Creating multiple tabs in PHP using the header function can be achieved by specifying the location in

I am attempting to open a new tab using Php code: header("location:print_register.php?recpt_no=".$recpt_no); In addition, I would like to open two tabs programmatically with the following code snippet: header("location:print_register.php?recpt_no=".$rec ...

What's the reason for this Ajax request taking such a long time to display on the

My webpage features dynamic content created by Ajax, refreshing every 30 seconds with new information from the database. The PHP side of things seems to be functioning properly, but I suspect there might be an issue either in my JavaScript code or within t ...

A helpful guide on presenting chart data in HTML table format using Chart.js

Is there a way to convert chart data into an HTML table upon button click using Chart.js? I have successfully created a line chart with Chart.js, with the x-axis representing colors and the y-axis representing votes and points. Here is a link to a workin ...

Using JavaScript to implement Gzip compression

As I develop a Web application that must save JSON data in a limited server-side cache using AJAX, I am facing the challenge of reducing the stored data size to comply with server quotas. Since I lack control over the server environment, my goal is to gzip ...

Utilize AJAX, jQuery, and Symfony2 to showcase array information in a visually appealing table format

I have a requirement to showcase data utilizing ajax and jQuery in a table on my twig file. The ajax call is made with a post request to the controller, where the controller attempts to input several rows from a csv file into the database. However, there ...

Is there a quicker method than using document.getElementById('element-id').innerHTML to retrieve content?

Currently, I am developing a user-friendly step-by-step wizard for my website to gather information about custom orders. Utilizing JavaScript, I have been tasked with updating the content of each "page" using the document.getElementById('element-id&ap ...

Storing user input from Vue.js in a JavaScript array for future use

Utilizing vue.js <template> <input id="email" v-model="email" type="text" placeholder="Email"> <input id="name" v-model="name" type="text" placeholder=" ...

refreshing datatables with updated data from a different endpoint

Need help reloading datatables with the new ajax feature? I suspect it might be a scope issue. function refreshTable(tableName, src) { var table = $('#'+tableName).DataTable({ 'bProcessing': true, 'bServerSide ...

The concept of CSS Parent Elements refers to the relationship

Is it possible to dynamically apply CSS style based on the parent property of a div element using JavaScript? Here is an example: <div clas="parent"> <div class="child"> <div class="x"></div> </div> </d ...

Using Node.js and Multer to update a file uploaded to MongoDB

I have a website that allows users to upload files, but I also want them to be able to edit those files. This would involve the user pressing "edit" and replacing the existing file in the database with a new one. Normally, you can use findByIdAndUpdate for ...