How can I access a store getter in Vue after a dispatch action has finished?

I am currently utilizing Laravel 5.7 in combination with Vue2 and Vuex.

While working on my project, I have encountered an issue where Vue is not returning a store value after the dispatch call completes. The workflow of my application is as follows:

  1. When I click a submit button, it triggers the validate() function within the component.
  2. The validate() function then dispatches to the "addLease" action, which interacts with the store API in a Laravel controller.
  3. Laravel handles data validation and responds with either errors or a success message.
  4. Upon receiving the response, the leaseStore state is updated accordingly through a commit operation.

My challenge lies in submitting a blank form, resulting in errors being returned – evident in the Network tab of Chrome DEV tools. Everything appears to be functioning correctly until the error needs to be stored in the leaseStore state. An error displayed in the console reads:

Uncaught (in promise) TypeError: Cannot read property 'leaseStore' of undefined

I suspect there may be a small oversight on my part, but pinpointing the mistake has proven difficult. It seems that there might be an issue when committing the error value to the leaseStore state, though I can't be certain.

API Call:

postLeaseStore: function(data){
    return axios.post('/api/lease',
        data
    );
}

Action:

addLease({ commit, state }, data) {
    commit('setLeaseStore', 0);

    LeaseAPI.postLeaseStore(data)
    .then( function( response ) {
        console.log('Success');
        commit('setLeaseStore', 1);
    })
    .catch( function(error) {
        console.log('Error');
        return commit('setLeaseStore', 3);
    });
}

Vue Component:

computed: {
    leaseStore() {
        return this.$store.getters.getLeaseStore;
    }
},
methods: {
    validate()
    {
        this.$store.dispatch('addLease', this.input).then(function () {
            console.log(this.leaseStore);
        });
    }
}

Answer №1

Your callback is losing the context of the Vue instance due to a scope issue. To resolve this, make use of an arrow function ()=> in the following manner:

    methods: {
     validate()
       {
       this.$store.dispatch('addLease', this.input).then(()=> {
        console.log(this.leaseStore);
      });
     }
   }

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

Ways to retrieve a property that is dynamically generated within a React component

In the code snippet below, I have registered the TextField name as M1.${index}.M13-M14 and it is marked as required. However, I am unable to locate the property accessor using errors[`M1.${index}.M13-M14`]?.type, which prevents the error from being gener ...

Leveraging Angular-translate with state parameters

My current challenge involves using angular-translate for localization. Everything is working smoothly except for translating data within state parameters. As an example, consider a state configuration like this: .state('about', { url: "/ ...

Steps for integrating Stanford's NLP into a web application

I have successfully developed a project utilizing Stanford's NLP API and models. Now, I am looking to integrate this Java-based project onto the web. After seeing the demo provided by Stanford-NLP, I am curious about the process they use to achieve th ...

Top method for detecting errors in Models? (Node.js + Sequelize)

Looking for a straightforward method to catch errors in an API using Node.js and Sequelize models? Take a look at this code snippet which utilizes async-await: const router = express.Router() const { Operations } = require('../models') router.po ...

Collect information from forms and save it to a mobile phone number

Is it possible to forward form field details to a cell phone number via text message? Here is the code I currently have for sending form data to an email address. If any adjustments need to be made, please provide instructions. <?php if(isset($_POST[ ...

Strange error message regarding ES6 promises that is difficult to interpret

Snippet getToken(authCode: string): Promise<Token> { return fetch(tokenUrl, { method: "POST" }).then(res => res.json()).then(json => { if (json["error"]) { return Promise.reject(json); } return new Token ...

Unable to view images on Wordpress theme

I am currently facing an issue where some images in my asset folder are not displaying properly when I convert my HTML/CSS/JS template to Wordpress. The main problem is with the image that should show up when you first visit the website. Below is the CSS c ...

Click once to expand all rows in the table with ease

I have successfully created a basic table using HTML. The table includes nested elements that are designed to open individually when clicked on the assigned toggle. Essentially, clicking on a '+' icon should reveal a sub-menu, and clicking on a & ...

Bidirectional communication between server and client using socket.io in node.js

I'm currently working on developing a server code in node.js where the client, running on a browser, will send data to the server when a specific ".on" event occurs. The task on the server side is to receive this incoming data from the client and then ...

How to integrate angular-ui-bootstrap with webpack

I'm attempting to integrate https://github.com/angular-ui/bootstrap with Webpack: import angular from 'angular'; import uiRouter from 'angular-ui-router'; import createComponent from './create.component'; import tabs fro ...

Is it possible to switch states in Angular UI Router without altering the URL?

The feature of multiple nested views in the ui-router is quite convenient as it allows for seamless transitions between different states within an application. Sometimes, there may be a need to modify the URL while navigating through states, while at othe ...

The Grid within the Container is presented vertically rather than horizontally

I followed the coding style exactly as shown in a recent tutorial on YouTube, where the cards were displayed in a row. However, when I implemented it, they are appearing strangely in a column. Why is this happening? The default should be inline. Even afte ...

Update the displayed image on the webpage based on information retrieved from the database

Can someone help me figure out how to change the clickable icon on getseats.php from available to unavailable when a seat's status is 0? I'm struggling with this and any advice would be appreciated. Here's the code I have: <?php $noerro ...

Mapping keys in a react component for efficient sorting

I'm facing some challenges when attempting to reorder keys from a state within my map function in React.. The original output is: monday : {1200: {…}, 1500: {…}, 1800: {…}, 2000: {…}, 2200: {…}, 0000: {…}, 0100: {…}, 0500: {…}, 0600: ...

Tips for Managing Disconnection Issues in Angular 7

My goal is to display the ConnectionLost Component if the network is unavailable and the user attempts to navigate to the next page. However, if there is no network and the user does not take any action (doesn't navigate to the next page), then the c ...

Incorporating JSON information into highcharts for advanced data visualization

If I were to utilize JSON code from a specific website, such as this one: "", in order to incorporate it into my highcharts implementation. The data seems to consist of x_min, x_max, and price_data values. What would be the best approach for creating hig ...

The value of the checked input with the name `nameofinput` is currently not defined

I'm having trouble passing the input value to another page. $( this ).attr( "href", '?module=module_progress_report&Subject='+ $('input[name=subject]:checked').val()+ '&Centre_Selected_ID='+ encodeURIComponen ...

Interdependent function calls between two functions

When faced with the task of recursively checking two objects with sorted keys, I came up with a solution involving two functions. buildObj - this function retrieves all unique keys from the objects, sorts them, and then calls buildObjKey for each key bui ...

What could be the reason behind Next.js attempting to import a non-existent stylesheet?

Lately, I've come across an issue where Nextjs is attempting to import a non-existent stylesheet (refer to the images below). I'm looking for guidance on how to resolve this error. Hoping to find a solution here, thank you Web browser console W ...

Display the content enclosed within the tags of a component within a designated div element of the

I am currently working on a Vue component that has the following structure: <template> <div class="message__overlay"> <div class="message__overlay-content"> <div class="message__overlay-content-top"> <spa ...