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

Obtain an indeterminate value from a variable

My situation involves a dynamic variable assigned from a service, requiring a real-time calculator to update another variable using its value. Below is the relevant code snippet: $scope.getSubTotalSCTax = function(){ TableService.checkOut('SubTo ...

Error: The function nodemailer.createTransport is not defined or does not exist

I'm currently working on integrating nodemailer into my nodejs application for sending emails. Check out the code below: var express = require('express'); var nodemailer = require('node-mailer'); var app = express(); app.post(&a ...

Top method for triggering an action on the client-side during Sign In with the help of Redux, React, and NextAuth

Currently, I am developing a web application that utilizes the Spotify API. My goal is to seamlessly load the user's playlists as soon as they log in using NextAuth. At the moment, there is a button implemented to trigger playlist loading, but it onl ...

Is there a way to streamline the process of dragging and dropping multiple files with C# selenium automation?

I have successfully implemented code to drag and drop a single image, but I am unsure about the necessary changes needed to support multiple file uploads. Can anyone provide assistance with this? Thank you. driver.Url = "http://example.com"; IWebEleme ...

Extract information from one webpage, proceed to the following page, and repeat the process, utilizing JavaScript on the site

Exploring various web scraping techniques, I've hit a roadblock and could use some assistance. Currently, my Python code successfully extracts data from the first page of my website. response = requests.get(url) soup = BeautifulSoup(r.text, 'ht ...

Exploring the limitations of middlewares in supporting independent routers

When I examine the code provided, it consists of three distinct routers: const Express = require("express") const app = Express() // Three independent routers defined below const usersRouter = Express.Router() const productsRouter = Express.Router() cons ...

a guide on expanding a submenu in a shiny dashboard sidebar without using automated functions

I am facing a challenge in manually expanding a submenu within a sidebar on shiny dashboard. The function updateTabItems does not seem to work with nested menus, only with normal menus. For example, when I click on 'Switch tab', it switches the ...

The C# MVC Controller is having difficulty retrieving decimal or double values from an Ajax POST request

Having trouble sending decimal or double values via ajax to my C# MVC Controller. The values always come through as null, even though they work fine when sent as strings or integers. Why is this happening? When checking the client's request, the corre ...

A TypeError was encountered: Attempting to read the 'substr' property of an undefined variable

Recently, I encountered an issue while working on a script with jquery.min.js version 1.4. The problem arose when I had to upgrade the script to version 1.9.1. Uncaught TypeError: Can not read property 'substr' of undefined. I need assistance i ...

What is the best way to use createElement in JavaScript to insert <p> and <span> elements within a <div>?

I am currently experimenting with generating sentences accompanied by draggable text boxes. To achieve this, I intend to construct the following HTML structure using JavaScript exclusively: <div> <p>Data1<span class = "smallBox droppabl ...

Having difficulty rendering JSON data on an HTML webpage

Currently, I am working on an API App that utilizes the Foursquare API. With the help of my getRequest function, I am able to obtain results in JSON format, which are then displayed in my console.log. However, the challenge lies in parsing the data from J ...

Tips for controlling numerous tabSlideOUt tabs on a single webpage

Is there a way to implement multiple tabSlideOut functionalities on a single page, similar to the examples provided in the following links: source code on GitHub and Fiddle Example? Specifically, I am looking to have tabs that can be toggled, ensuring tha ...

Steps to retain localStorage data while redirecting to another external webpage

Encountering an issue with saving localStorage data across redirects. See the code snippet below: // Invoke newSitelogin(). Save response(credentials) in localStorage. Redirect to new URL. newSitelogin({ uuid, password }) .then(() => { window.ope ...

In the Vercel production environment, when building Next.js getStaticPaths with URL parameters, the slashes are represented as %

I've encountered an issue while implementing a nextjs dynamic route for my static documentation page. Everything works perfectly in my local environment, and the code compiles successfully. However, when I try to access the production URL, it doesn&ap ...

Creating a form submission event through Asp.net code behind

Is there a way to change the onsubmit parameter of a form in an asp.net project, specifically from the master page code behind of a child page? I am interested in updating the form value so that it looks like this: <form id="form1" runat="server" onsu ...

JQuery form serialize not triggering in Internet Explorer

I've encountered an issue with a form inside a jQuery dialog that is not submitting properly in Internet Explorer. The form functions correctly in Chrome and Firefox, sending data to my MVC controller without any issues. However, when using IE, it on ...

JQuery click event does not play nicely with Javascript array splice functionality

When using for loops, I noticed that array.splice doesn't seem to be working as expected. The array remains unchanged. I tried moving things around and found that it still doesn't work in Chrome. var menu =['#men','#wmen',&a ...

Easy ways to manipulate the style of array components in Vue.js

Hey there all you programmers, I'm reaching out to see if any of you have insight on how I can modify the style of a specific component within an Object array. This is the code snippet: <template> <div> <ul> <li v-fo ...

Leverage Arrays with Bootstrap SelectPicker in Javascript

I am looking to populate a Bootstrap SelectPicker with values from an array. I am unsure of how to loop through the array to extract the values. Currently, I have manually added values to the SelectPicker like this. <!DOCTYPE html> <html> < ...

Quantifying the passage of time for data entry

Looking to create a quiz form where I can track how long it takes users to input/select answers. I attempted the following code but the timing seems off: $('input, select').on('focus', function(event) { el = $(this); name ...