Utilizing Vuex to Access a Component's Property in Vue

Utilizing Vuex in my app is integral for executing asynchronous tasks, such as logging a user into the application. Upon successful login and execution of axios.then(), I aim to notify the component from which I invoked this.$store.dispatch('login', {username: userObj.username, password: userObj.password});


    data() {
        test: false
    },

    methods: {

        login() {
            const userObj = {
                username: this.username,
                password: this.password
            };
            console.log(userObj);
            this.$store.dispatch('login',
                {
                    username: userObj.username, password: userObj.password
                });
        }
    },

Vuex:

const actions = {
    login({ commit }, authData) {
        axios.post('/login', {
            username: authData.username,
            password: authData.password
        })
            .then(resp => {
                console.log(resp);
                localStorage.setItem('token', resp.data.authToken);
                localStorage.setItem('userId', resp.data.id);
                localStorage.setItem('user', resp.data);
                commit('storeUser', resp.data);
                router.replace('/dashboard');
            })
            .catch(e => {
                console.log(e);
                alert('Something went wrong, try again')
            });
    },
}

In the .then() method within Vuex, I am looking for assistance in altering the test property to true in my component. Any advice or solutions would be greatly appreciated!

Answer №1

To make use of asynchronous behavior in vuex actions, you can return a Promise:

const actions = {
    login({ commit }, authData) {
        return new Promise((resolve, reject) => {
            axios.post('/login', {
                username: authData.username,
                password: authData.password
            })
                .then(resp => {
                    console.log(resp);
                    localStorage.setItem('token', resp.data.authToken);
                    localStorage.setItem('userId', resp.data.id);
                    localStorage.setItem('user', resp.data);
                    commit('storeUser', resp.data);
                    router.replace('/dashboard');
                    resolve(resp);
                })
                .catch(e => {
                    console.log(e);
                    alert('Something went wrong, try again')
                    reject(e);
                });
        })
    },
}

You can handle the promises from actions seamlessly when dispatching them:

// Example usage inside a component
this.
  $store.
  dispatch('login', {username: userObj.username, password: userObj.password})
  .then(resp => { /* Handle response here using component data and methods */);

Answer №2

One key aspect of utilizing the Vuex store is to avoid directly modifying your component's props or data. Instead, the recommended approach is to store the necessary data in Vuex and keep track of any changes or updates within the component. For instance, within your login action, you might include something along these lines:

// Implement the necessary changes within the store
commit('storeTest', true);

Subsequently, within the component:

computed: {
    // Retrieve the stored value from the Vuex store
    test: () => {
        return this.$store.test;
    }
},

Answer №3

To utilize Vuex actions effectively, it is important to understand that they are thennable. This means that when dispatching an action in a component, the structure should resemble something along these lines:

this.$store.dispatch('login', { username: userObj.username, password: userObj.password }).then(res => {
// handling response
});

Additionally, the action must return the response for it to function as intended.

const actions = {
    login({ commit }, authData) {
        axios.post('/login', {
            username: authData.username,
            password: authData.password
        })
            .then(resp => {
                console.log(resp);
                localStorage.setItem('token', resp.data.authToken);
                localStorage.setItem('userId', resp.data.id);
                localStorage.setItem('user', resp.data);
                commit('storeUser', resp.data);
                router.replace('/dashboard');
                return resp
            })
            .catch(e => {
                console.log(e);
                alert('An error occurred, please try again')
            });
    },
}

Answer №4

When dealing with mutations, you have the option to utilize the subscribe method or the subscribeAction method for actions as outlined below:

mounted() {
    this.$store.subscribeAction({
        before: (action, state) => {
            switch (action.type) {
                case 'login':
                    this.test = false;
                    break;
            }
        },
        after: (action, state) => {
            switch (action.type) {
                case 'login':
                    this.test = true;
                    break;
            }
        }
    });
}

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

Detecting when the page is done loading in CasperJS with the help of $.ajaxStop()

During my CasperJS tests, I've relied on waitForSelector() to check if a page has finished loading, including all asynchronous AJAX requests. However, I'm interested in finding a more standard approach for waiting for page load. Is it possible to ...

Steps to create a toggle click event

I've been attempting to create a toggle click event using the code below: HTML <a class="load" data-gallery="123456" style="cursor: pointer;"><h2><p>example</p></h2></a> <div id="123456"> </div> j ...

What causes my browser fingerprint to consistently remain unchanged?

declare var Fingerprint2: any; @Component({ selector: 'my-app', template: `Hello`, }) export class App { constructor() { new Fingerprint2().get(function(result, components){ console.log(result); // Device fingerprint as a hash va ...

Modify the row's background color after clicking the delete button with jquery

Greetings, I am facing an issue with changing the color of a row in a table when clicking on a delete button. Despite trying various methods, I have not been successful. How can I modify the ConfirmBox() method to change the row's color? Your assistan ...

Navigating the complexities of integrating Angular-based JS select/input values using CefSharp Offscreen on an external website: A comprehensive guide

I have encountered some challenges with setting input values on a third-party webpage that utilizes Angular for field validation. When attempting to set the value attribute using Chrome or CefSharp, the value does not update as expected. To work around th ...

Audio waves visualization - silence is golden

I am attempting to create a volume meter, using the web audio API to create a pulsation effect with a sound file loaded in an <audio> element. The indicator effect is working well with this code; I am able to track volume changes from the playing aud ...

Incorporating fresh JSON information into an established database

I'm currently facing an issue with adding new data (from JSON) to an existing table using jQuery. Within my HTML, there's a sample table structure like this: <table data-role="table" data-mode="columntoggle" class="ui-responsive" data-column ...

Endless Loop of Http Redirects in Node.js with Express

I need assistance with the code below which is meant to redirect all http traffic to https. // Implement redirect logic to ensure usage of https in production, staging, and development environments app.use((req, res, next) => { // Do not redirect to h ...

Storing audio files in Firebase Cloud Database and displaying them in React js + Dealing with an infinite loop problem

Lately, I've been encountering a persistent issue that has proven to be quite challenging. Any assistance would be greatly appreciated. Thank you in advance. The objective is to create a form that allows for the easy addition of new documents to the ...

Do you have any recommendations for a jQuery plugin that can create a sleek horizontal scrolling image gallery?

Recently, I came across the Smooth div scroll plugin developed by Thomas Kahn, and it fits my requirements perfectly. However, I have encountered a bug that seems to be persisting. The issue arises when both mousewheel scroll and touch scroll are enabled s ...

What could be the reason that step 3 of the AngularJS Tutorial is not functioning correctly?

During Step 3 of the AngularJS Tutorial, an additional e2e test is recommended to enhance the example: it('should display the current filter value within an element with id "status"', function() { expect(element('#status').text() ...

Animating Chart.js 2 from right to left instead of from top to bottom

Here is the issue demonstrated in the jsfiddle below. Initially, the data inserts work well. However, when the data set reaches a cap of 10, an unwanted behavior occurs where the data points are animated top-down instead of moving leftward. This can be qu ...

Linking chained functions for reuse of code in react-redux through mapStateToProps and mapDispatchToProps

Imagine I have two connected Redux components. The first component is a simple todo loading and display container, with functions passed to connect(): mapStateToProps reads todos from the Redux state, and mapDispatchToProps requests the latest list of todo ...

Summernote - When validating text, it is shown as raw HTML

I have integrated Codeigniter with Summernote on the frontend. In a form, if certain fields are left empty, the same page reloads for validation checking. The JavaScript and CodeIgniter code I am using is as follows: $(window).load(function(){ &l ...

Inserting items into an array based on the user-specified quantity

Suppose I have an array with 8 elements. If the user enters a number greater than the length of the array, how can I dynamically add the remaining items to the list? For example: If my array length is 8 and the user enters 15, how can I add 7 items to th ...

selection menu and advancement gauge

While working on my code, I have a task where I need to make the progress bar move a specific amount when a name is clicked based on the option's value. <!DOCTYPE html> <html> <head> <title>testinggg</title> &l ...

The route seems to be downloading the page instead of properly rendering it for display

I'm facing a simple issue with my Express page - when I navigate to the FAQ route, instead of displaying the page it downloads it. The index page loads fine, and the FAQ page is the only other page available at the moment. I am using EJS templating, a ...

Troubleshooting my HTML5 local storage issues for optimal functionality

I've been working on using HTML5's localstorage to save two variables and load them upon page refresh, but I seem to be encountering some issues when trying to load the saved items: Variables in question: var cookies = 0; var cursors = 0; Savi ...

Eliminate unnecessary spaces in Vue with Moment

Utilizing moment in this way: pages/index.vue <template> <div class="box"> {{ item.updateDate | moment("from", "now") }} </div> </template> An illustration of item.updateDate would be 1580564625000. I'm empl ...

Alternative for document.ready in AngularJS when outside of AngularJS

I am currently developing a small Chrome extension that will interact with an Angular website. I have managed to successfully detect full page reloads using $(document).ready(), but I am facing issues when it comes to detecting page changes triggered by ng ...