State in Vuex is not kept intact after redirection to another page

Inside my Vue.js application, I have created a method for logging in users. This method sends a POST request to the server with the username and password, stores the returned data in Vuex store, and then redirects the user to the home page:

   login: function () {
            axios.post( this.BASE_URL + "/login", {
            username: this.username,
            password: this.password,
          }).then( (res) => { 
                this.$store.commit('setIsAuthenticated', true);
                this.$store.commit('setToken', res.data.token);
                this.$store.commit('setPhoto', res.data.photo);
                this.$store.commit('setUsername', res.data.username);
                window.location.href = '/home'; //<-The problem     
          }

Here are some example mutations used in the application:

setToken: function (state, token) {
    state.token = token;
    },
setUsername: function (state, username) {
    state.username = username;
},

In the App.vue (root component), the values stored in Vuex are retrieved as computed properties:

  computed: {
    isAuthenticated () {
    return this.$store.state.isAuthenticated;
    },

    token () {
        return this.$store.state.token; 
    } ,

An issue arises when the page is redirected to /home, causing all stored values to be emptied. Even though the login process is successful and the values are set in the Vuex store before redirection, they get lost upon arrival at the home page. I am seeking assistance in understanding why this occurs and how to resolve it.

UPDATE: I am using vue-router with designated routes defined in routes.js:

import webLogin from './components/webLogin.vue';
import showAll from './components/showAll.vue';

export default [ 
  {path:'/', component: showAll },
  {path:'/add', component: addJoke  }  ,
  {path: '/login', component: webLogin},  
]

Answer №1

The Vuex state stores data in memory. When you use window.location.href to redirect, it will cause a complete page refresh, resulting in the loss of your current state. To navigate without losing state, it is recommended to utilize Vue router. You can find more information about Vue router here.

For instance, if you want to redirect to the route named Home, you can do so as follows:

this.$router.push({ name: 'Home' });

Answer №2

Utilize Vuejs for seamless page navigation instead of manual methods

It is crucial to use Vuejs routes for navigating between pages in order to ensure the preservation of state. Consider the following scenarios:

  1. If you set the state in the store on one page, then directly enter the URL of another page into the browser and press enter, the state will not be preserved and will revert to default values.
  2. On the other hand, if you set the state in the store on one page and navigate to another page using Vuejs routes, the state will be retained.

For Nuxtjs:

<nuxt-link to="discussion/1">Go to Discussion</nuxt-link>

For Vuejs:

<router-link to="discussion/1">Go to Discussion</router-link>

By utilizing Vuejs routes, the state in the store will be preserved consistently.

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

What is a functional component in defineSlots?

With the latest version of Vue SFC (3.3+), slot scope has become type safe with the introduction of defineSlots. Is there a way to achieve the same type safety for slots in functional components as well? export default defineComponent({ name: 'MyCompo ...

Steps for inserting a word into an element using jQuery

How can I use JQuery to insert English words into an element? Before: رایجترین نوع این پارامتر کلاس پایه eventArgs می باشد. After : رایجترین نوع این پارامتر کلاس پایه <bdo>eventArgs& ...

Uploading Files with Vuetify 2 v-file-input and AxiosIn this tutorial, we

After researching extensively on the topic, I reviewed questions such as file-upload-in-vuetify and vuetify-file-uploads, but unfortunately, the solutions provided did not work for me. My current challenge involves utilizing Vuetify 2's <v-file-in ...

Verify the presence of a specific select option using text in jQuery version 1.7

Looking at the following snippet of HTML: <select id="sel"> <option value="0">Option1</option> <option value="1">Option2</option> <option value="2">Option3</option> <option value="3">Option4</option> & ...

Reducing image file sizes in Ionic 3

I have been struggling to compress an image client-side using Ionic 3 for the past couple of days. I have experimented with: ng2-img-max - encountered an error when utilizing the blue-imp-canvas-to-blob canvas.toBlob() method (which is a dependency of ng2 ...

Incorporating JavaScript/JSON into your Ebay listings to seamlessly receive user-selected choices

There has been a trend among Ebay users to incorporate dynamic data fetching and sending from external sources in their listings. This could be for implementing a shipping calculator or offering different product variants through dropdown lists. You can c ...

Converting a jQuery DOM element into a string representation

Currently, I am working with a textarea that contains the contents of an HTML file. This textarea includes all elements of my HTML page such as doctype, head, html, etc. My goal is to save the content of the textarea into a DOM variable using $.parseHTML: ...

Iterating through objects in an array using JavaScript should only happen after the current object

As an illustration: Starting from [x0,x1,x2,x3] - x0 compares itself to x1,x2 and x3. x1 compares itself to x0, x2 and x3. And so forth... To [x0,x1,x2,x3] - x0 compares itself to x1,x2 and x3. x1 compares itself to x2 and x3 only. x2 only compares ...

Utilizing Node Mailer and Sendgrid to send emails in an Angular MEAN stack project with the angular-fullstack framework generated by Yeoman

Trying to figure out the best location for the code responsible for sending an email through a contact form in my Angular App using angular-fullstack MEAN stack from Yeoman. I managed to implement the email sending logic in the app.js file on the server s ...

Angular Transclude - ng-repeat fails to iterate over elements

Recently, I've been experimenting with Angular directives and encountered a peculiar issue... Check out the code snippet below: <!DOCTYPE html> <html> <head> <title>Directive test</title> <script type="text/ja ...

What is the process of transferring an object to a different scope by utilizing checkboxes and Ajax?

I find myself lost in contemplation. I have a checkbox that I want to utilize to move a corresponding object to another area on my page. Furthermore, I am interested in transferring only one specific field of this checked object. In the past, I utilized Aj ...

Issue: Compilation unsuccessful due to an error in the Babel loader module (./node_modules/babel-loader/lib/index.js). Syntax error

I'm currently exploring how to integrate the Google Maps Javascript API into my VueJs project without relying on the vue2-google-maps package (as it seems too restrictive to me). Here's what I've done so far, after registering my Vue compon ...

The fitBounds and panToBounds functions in react-google-maps fail to properly adjust the map's size

const Map = withGoogleMap(props => { const { activeMarker, zoom, center, showInfoWindow, products } = props; const [selectedPlace, setSelectedPlace] = useState(null); // Code to iterate through items and adjust map size, center, and zoom to inclu ...

Reduce and combine JavaScript files without the need for Grunt or Gulp

My project involves working with over 50 JavaScript files that I want to combine and compress to optimize file size and minimize HTTP requests. The catch is, the client's system does not have Node or npm installed. How can I accomplish this task witho ...

Generate a custom Elementor shortcode dynamically using JavaScript

I have a custom-built website using WordPress and Elementor. I am running code through the html element in Elementor to display dropdown menus. When a value is selected from each dropdown and the button is clicked, the values are stored in variables and th ...

How can you set the listbox in Sumo Select to always be open?

https://i.sstatic.net/fkiHB.png Is there a way to ensure the listbox is always open by default, as if the user had clicked? ...

Heroku is rejecting the Discord token, but it is functioning properly in Visual Studio Code

I am facing an issue with an invalid token error on Heroku, even though the token in my main.js file on Git is the same as the one I have in Visual Studio Code. Interestingly, Heroku claims it's an invalid bot token while the Discord bot token from VS ...

Verify if a set of Radio buttons contains at least one option selected

Need help with validating a Feedback Form using either JQuery or Javascript. The requirement is to ensure that every group of radio-buttons has one option selected before the form can be submitted. Below is the code snippet from form.html: <form id=&ap ...

Pushing state history causes browser back and forward button failure

I'm currently utilizing jQuery to dynamically load content within a div container. On the server side, the code is set up to detect if the request is being made through AJAX or GET. In order to ensure that the browser's back and forward buttons ...

Something is overriding the style created by makestyle material UI that I had implemented

How can I increase the importance of my makeStyles classes over default Material UI styles? Here is my code: import { createTheme, ThemeProvider } from '@mui/material/styles'; import { makeStyles, createStyles } from '@mui/styles'; co ...