After logging in or out, the Vuex state remains unchanged

I need to display different buttons in the Header component based on the user's authentication status.

Header.vue

<template>
        <div class="utf_right_side">
          <div class="header_widget">
            <router-link :to="{name:'login'}" class="button border sign-in popup-with-zoom-anim" v-if="!isAuth"><i class="fa fa-sign-in"></i>Login</router-link>
            <a class="button border sign-in popup-with-zoom-anim" v-if="isAuth" href="" @click.prevent="logout" :key="componentKey"><i class="fa fa-sign-in"></i>Logout</a>
            <a href="dashboard_add_listing.html" class="button border with-icon"><i class="sl sl-icon-user"></i> Add Listing</a></div>
        </div>
</template>

<script>
    import {mapActions} from 'vuex'
    export default {
        name:"default-layout",
        data(){
            return {
                user:this.$store.state.auth.user,
                isAuth: this.$store.state.auth.authenticated,
            }
        },
        methods:{
            ...mapActions({
                signOut:"auth/logout"
            }),
            async logout() {
                await axios.post('/logout').then(({data})=>{
                    this.signOut();
                    this.$parent.forceRerender();
                })
            },
        },

    }

</script>

The isAuth variable from the Vuex state determines which buttons are displayed. However, after logging in, the state remains unchanged and displays the old button instead of the authenticated one. A manual page refresh (F5) correctly shows the authenticated button.

Login.vue:

<script>
import { mapActions } from 'vuex'
export default {
    name:"login",
    data(){
        return {
            auth:{
                email:"",
                password:""
            },
            validationErrors:{},
            processing:false
        }
    },
    methods:{
        ...mapActions({
            signIn:'auth/login'
        }),
        async login(){
            this.processing = true
            await axios.get('/sanctum/csrf-cookie')
            await axios.post('/login',this.auth).then(({data})=>{
                this.signIn()
            }).catch(({response})=>{
                if(response.status===422){
                    this.validationErrors = response.data.errors
                }else{
                    this.validationErrors = {}
                    alert(response.data.message)
                }
            }).finally(()=>{
                this.processing = false
            })
        },
    }
}
</script>

Vuex auth.js included in index.js Vuex file:

import axios from 'axios'
import router from '@/router'

export default {
    namespaced: true,
    state:{
        authenticated:false,
        user:{}
    },
    getters:{
        authenticated(state){
            return state.authenticated
        },
        user(state){
            return state.user
        }
    },
    mutations:{
        SET_AUTHENTICATED (state, value) {
            state.authenticated = value
        },
        SET_USER (state, value) {
            state.user = value
        }
    },
    actions:{
        login({commit}){
            return axios.get('/api/user').then(({data})=>{
                commit('SET_USER',data)
                commit('SET_AUTHENTICATED',true)
                router.push({name:'home'})
            }).catch(({response:{data}})=>{
                commit('SET_USER',{})
                commit('SET_AUTHENTICATED',false)
            })
        },
        logout({commit}){
            commit('SET_USER',{})
            commit('SET_AUTHENTICATED',false)
        }
    }
}

When a user logs in, the login method in auth.js sets the correct state as shown here:

        commit('SET_USER',data)
        commit('SET_AUTHENTICATED',true)|

Even after being redirected to the home route, the Header still displays the old button. Only a manual page refresh correctly shows the authenticated button.

Answer №1

Instead of accessing state directly with

this.$store.state.auth.authenticated
, it's recommended to utilize getters.

import { mapGetters } from 'vuex'

You can then use the getter in a computed property for reactive behavior:

 computed: {
  ...mapGetters({ isAuth: 'auth/authenticated' }),
 },

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

Angular and JS do not have the functionality to toggle the split button

I have a question that seems similar to others I've seen, but I haven't found a solution yet. Can someone please review my code? In the component, I have {{$ctrl.init}} and {{$ctrl.people}} assigned. I am sure this assignment is correct because ...

The title of the Electron application remains consistent

My application is being packaged using electron-packager, but it's not changing its name and still displays "Electron." It's supposed to use the productName in my package.json file, but for some reason, it doesn't change. Even after creati ...

.scss compiling with errors

Recently, I embarked on a new Vue(3) project. Within this project, I have set up some basic styling in the App.scss file and created a HomeView.vue with a corresponding HomeView.scss file (located in the /src/views/Home directory). The styling from both fi ...

The website's responsive design functions flawlessly when viewed on a desktop browser or mobile-simulator for Safari and Mozilla Firefox. However, when accessed on an actual smartphone using Android or iOS

I've been experimenting with different lines of code, but I'm struggling to pinpoint the error as my code functions on a desktop and should also work on mobile devices... <meta name="viewport" content="width=device-width, initial-scale=1, max ...

Ways to dynamically emphasize text within ngFor loop

Within my ngFor loop, I have a set of rows. <div *ngFor="let block of data;"> <div class="class-row"> <div class="left">A Label:</div> <div class="right">{{block.key1}}</div> </div> <div class="clas ...

Tips for transmitting and utilizing information in ejs or jade with a node js server

I'm currently working on a project where I need to send data stored in localstorage from an ajax call to a node js server. The goal is to use the retrieved data to customize an html page using ejs or jade templates. I've attempted to send my data ...

Instructions on how to make a radio button selected when clicked are as follows:

My radio button is currently checked, but I would like it to be onclicked because there is a Javascript function that uses the on.click function. Are there any possible methods or examples to achieve this? <label style="margin-left:177px;">Order Ty ...

An error is raised when attempting to refactor [].concat.apply([], [x]) to [].concat(x)

When attempting to refactor Array.prototype.concat.apply([], [x]) to [].concat(x), I encountered the following error message: No overload matches this call. Overload 1 of 2, '(...items: ConcatArray<never>[]): never[]', gave the following ...

Issues with data within a Vue.js pagination component for Bootstrap tables

Currently, my table is failing to display the data retrieved from a rest api (itunes), and it also lacks pagination support. When checking the console, I'm encountering the following error: <table result="[object Object],[object Object],[object Ob ...

Determining the Next Available Date from JSON Data

I have a task of using a JSON response from the Eventbrite API to showcase the upcoming event tour date. The goal is to automatically calculate this date based on the current time, identifying the next event after the current moment. Below is the JSON res ...

Error in Nightwatch.js: window object does not exist

I am currently attempting to utilize Nightwatch for testing a React application that is integrated with React-Router. Upon running my test with Nightwatch, I have encountered an issue where window appears to be undefined. In order to verify the availabil ...

Retrieve the price of a span element based on the selected radio button using jQuery

I have a span with the class .amount, and now I want to extract the price from that span. $('.dimension-layer-dimension').click(function() { // Here is my JavaScript attempt var price4 = $(this).find('radio:checked').data(&apo ...

Alerting on Synchronous XMLHttpRequest within an asynchronous function

Upon utilizing my browser (specifically the JQuery framework), I noticed a warning being printed to the console: The warning indicates that Synchronous XMLHttpRequest on the main thread is no longer recommended due to negative effects on user experience ...

What is the reason behind Angular's refusal to automatically bind data when an object is cloned from another object?

Check out this simple jsfiddle I made to demonstrate my question: fiddle Here is the HTML code snippet: <div ng-controller="MyCtrl"> <div ng-repeat="p in products"> <span ng-click="overwrite(p)">{{ p.id }}: {{ p.name }}& ...

Leveraging jQuery's .animate method to create engaging search box animations

Greetings esteemed individuals... I am currently working on enhancing the search component for my application... http://jsfiddle.net/SkyKOG/K8utq/24/ input{ display:none; width:0px; color:#999; } Initially, I only had a simple search box so ...

Guide to utilizing JavaScript and JQuery for retrieving a PDF from a specific URL and subsequently uploading the file to another website

I have a link to a PDF file: http://www.example.com/HelloWorld.pdf My objective is to download the file using JavaScript/JQuery/AJAX and temporarily store it in the browser, without saving it on the user's machine. Then, I want to POST it to . To ac ...

Waiting for a function to finish until a modal window is closed in ReactJS

I have a situation in my app where I need to display a pop-up after a form submission. I want the function to wait for the pop-up to be closed before continuing with the rest of the code execution. Here is the pseudo-code: const onSubmit = useCallback(asy ...

Utilize the power of the Express-fileupload library to seamlessly upload images directly to your AWS S3 bucket

I'm in need of assistance - I want to utilize the express-fileupload library to upload my file and image to an AWS S3 bucket using a restful API. Any help would be greatly appreciated! ...

The power of Angular controllers lies in their ability to facilitate two-way

Currently, I have a controller that acts as a wrapper for ui-router and manages its flow, similar to a menu bar. When a user clicks on a menu item, a function is triggered that changes the ui-router state and broadcasts an event to the inner controllers. E ...

Detect the initial collision exclusively (Collision detection using raycasting)

I am currently working on a never-ending runner game where a character is positioned at (0,0) and can only move along the X-axis by using arrow keys or the mouse. There are two different types of objects moving from z = -10000 towards the character, and on ...