Updating route from action within Vuex Store

Exploring ways to trigger a route change from the store. I attempted to import router directly into the store and use the following code:

LOG_OUT({commit}){
  commit('LOG_OUT__MUTATION');

  router.push({
   name: 'Login' 
  })
}

Unfortunately, this approach did not yield the desired result.

I am hesitant to handle route changes within components as it would demand authentication checks and route changes in every component, which feels overly burdensome.

Edit:

The LOG_OUT__MUTATION function clears the token stored in the state.

Answer №1

I finally cracked the code.

End Result

To implement this in your store, all you need to do is import the router:

import router from '@/router/index'

actions: {

  LOG_OUT({commit}){
    commit('LOG_OUT__MUTATION');

    router.push({
      name:'Login'
    })
  }

}

From another section of my app, I imported the store and executed an action:

import Store from '@/store/store'

myFunction () {
  Store.dispatch('LOG_OUT');
}

Original Approach

This was how I applied Daksh Miglani's solution successfully. In my store.js file, here is what I had:

export const forceLogout = (commit) => {

  return new Promise((resolve, reject) => {
    commit('LOG_OUT__MUTATION');
    resolve();
  })

}

export default new Vuex.Store({
  actions,
  mutation
})

In another part of the app (helpers.js), I included the following:

import Store from '@/store/store'
import { forceLogout } from '@/store/store'
import router from '@/router/index'

forceLogout(Store.commit)
  .then(() => {
    debugger;
    router.push({
      name:'Login'
    })

  }).catch((error) => {
     console.log(error)
  })

Answer №2

Hey there, I've got a handy solution for you:

To start off, create a store commit function like the one below:

export const performLogout = ({commit}) => {
  return new Promise((resolve, reject) => {
    commit('LOG_OUT__MUTATION');
    // After clearing, resolve or reject the promise
    resolve();
  });
}

This function will generate a promise that can be utilized within your logout process, allowing you to first clear data before logging out.

Next, integrate this function into your logout feature:

...

  logout() {
    performLogout().then(() => {
      this.$router.push({
       name: 'Login' 
      })
    })
  }

...

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

AngularJS function orderBy reverses the array instead of sorting it

I encountered an issue where, after clicking the 'order button', the table does not order as expected. Instead, it reverses all the td elements. For example, 'A', 'C', 'B' becomes 'B', 'C', "A". I ...

Opening a Text File via an ASPX Web Page

Currently, I am immersed in a Web Pages project. The goal is to retrieve text from a Text File and display it within a div element. To achieve this, I utilized the ajax xmlhttprequest method, following a tutorial available at http://www.w3schools.com/ajax/ ...

Arranging the elements in my footer for optimal display

My footer layout expands and the lists in each column become misaligned as I add more links to it. I want to make sure that the lists for each column are aligned horizontally on the same row, with the title of each column also in the same row. levi | ...

Google Cloud's implementation of the "Vue+S3+Lambda" architecture

My VueJs single page website currently has very few transactions, prompting me to explore implementing it with a serverless architecture. One recommended approach for a basic Web Application on AWS includes: Vue App uploaded on AWS S3 Backend connection ...

What is the best approach for creating a test that can simulate and manage errors during JSON parsing in a Node.js

My approach to testing involves retrieving JSON data from a file and parsing it in my test.js file. The code snippet below demonstrates how I achieve this: var data; before(function(done) { data = JSON.parse(fs.readFileSync(process.cwd() + '/p ...

Testing mutations in vuex modules can be a crucial aspect of ensuring the stability and

Previously, my mutation tests were functioning properly before incorporating vuex modules: import mutations from '@/vuex/mutations.js' import vueAuthInstance from '@/services/auth.js' import { IS_AUTHENTICATED, CURRENT_USER_ID } from & ...

Enhance the performance of React code by refactoring it

Having recently started coding in React for a new organization, I find that the code in my component has grown lengthy and the submithandler method is causing multiple array iterations. Is there a way to refactor the code for better performance? The data t ...

Managing a promise and using async/await functions

Having an issue with my node and express function router.post('/', async (req, res) => { const playlist = new Playlist({ song: req.body.song, artist: req.body.artist }) try { const newPlaylist = await play ...

appending a set of parameters to a website address

I am currently developing an app in a Node/Express/Jade environment. Imagine that I launch my app and navigate my browser to the following URL: /superadmin/?year=2012 Upon reaching this page, I encounter a list of objects sorted in a default order. Ther ...

JavaScript's getElementById function may return null in certain cases

I am studying JavaScript and I have a question about the following code snippet: document.getElementById('partofid'+variable+number). Why isn't this working? Check out these examples and JSfiddle link. I want the "next" button to remove th ...

I am looking to transform CSV data into XLSX file format, upload it to AWS, and obtain the corresponding URL

I am currently in the process of converting a JSON file to CSV. My next step is to convert this CSV file to XLSX data and upload it to AWS to retrieve the link. Convert CSV to XLSX const xlsxFilePath = 'path/to/transaction_data.xlsx'; await csvto ...

Encountering problems with createMediaElementSource in TypeScript/React when using the Web Audio API

Currently, I am following a Web Audio API tutorial from MDN, but with a twist - I am using TypeScript and React instead of vanilla JavaScript. In my React project created with create-react-app, I am utilizing the useRef hook to reference the audio element ...

The Vue application combined with TypeScript is displaying an empty white screen

I've enrolled in a Vue + Firestore course, but I'm attempting to use TypeScript instead of conventional JavaScript. The basic setup is complete, however, my app displays a blank page when it should be showing a simple header text from the App.vue ...

Ways to retrieve child state in React?

After creating my own form component with a render() method that looks like this: render() { return ( <form onSubmit={this.onSubmit} ref={(c)=>this._form=c}> {this.props.children} </form> ) } I enabled ...

The URL provided for the Ajax HTTP request is not accurate

Consider the following JavaScript code: <script type="text/javascript" charset="utf-8> function goForLogin() { var xmlhttp; xmlhttp=new XMLHttpRequest(); xmlhttp.open("POST","/account/login",true); xmlhttp.s ...

Why is the second row of inputs not displaying in Vue.js?

I am currently developing a Single Page Application (SPA) that includes options with variants, similar to the image shown below: [1]: https://i.sstatic.net/82I5U.png However, I have encountered an issue where the second row of inputs for variants is not b ...

Moving an item to the top of an array in JavaScript/Vue.js: A simple guide

const a = [{ "iso2": "KH", "countryName": "Cambodia", "nationality": "Cambodian" }, { "iso2": "KI", "countryName": "Kiribati", "nationality": "I-Kiribati" }, { "iso2": "KM", "countryName": "Comoros", "nationality": "Como ...

"Using the power of jQuery to efficiently bind events to elements through associative

I am attempting to link the same action to 3 checkboxes, with a different outcome for each: var checkboxes = { 'option1' : 'result1', 'option2' : 'result2', 'option3' : 'result3', }; ...

Obtain a report using a variety of different conditions

My database has a table with the following fields: TPI CLICKS IMPRESSION CLASSIFY I am looking to retrieve 3 specific results: 1) Calculate SUM(CLICKS)/SUM(IMPRESSION) * 100 GROUPED BY TPI 2) Calculate SUM(IMPRESSION) WHERE CLASSIFY = "XYZ" GROUPED BY ...

I find the SetInterval loop to be quite perplexing

HTML <div id="backspace" ng-click="deleteString(''); decrementCursor();"> JS <script> $scope.deleteString = function() { if($scope.cursorPosVal > 0){ //$scope.name = $scope.name - letter; ...