Why isn't the view reflecting changes made to the store state after updates? Vue.js

I recently started using vue js to develop applications. I have successfully implemented a function that logs in the user by storing tokens received from the back-end in local storage, and checks for token validity. Everything was working fine until I decided to incorporate vuex to access user status anywhere in the app. However, I am facing an issue where the view is not updating after state changes. I have spent several hours troubleshooting with no luck. Is there a way to update the view without having to refresh the page?

Below is a snippet of the code I am currently working on. While it may seem like a jumble of variables displayed on screen, it is purely for testing purposes:

In my component

<p>Current token : {{ tokenToCheck }}</p>
    <p>{{ isValid }}</p>
    <p>{{ loggedIn }}</p>
    <p> {{ test }} </p>
    <div class="alert alert-success" v-if="loggedIn"><p>You are logged in</p></div>

store.js

import Vue from 'vue'
import Vuex from 'vuex'
import jwt from 'jsonwebtoken'

Vue.use(Vuex);

export const store = new Vuex.Store({
    state: {
        tokenToCheck: localStorage.getItem('token'),
        isValid: 'test',
        isLogged: true
    }, 
    getters: {
        isLogged: (state) => {
            return state.isLogged; 
        }
    },
    mutations: {
        CHECK_TOKEN(state) {
            try{
                jwt.verify(state.tokenToCheck, 'RANDOM_TOKEN');
                state.isValid = 'ok';
                state.isLogged = true;
                return true;
            } catch(error) {
                console.log(error);
                console.log(state.tokenToCheck);
                console.log('erreur test token'); 
                state.isValid = "expiry"; 
                state.isLogged = false;
                return false;
            }
        }
    }
});

Computed properties in my component

export default {

  name: 'Home',
  data() {
    return {
      pseudo: '', 
      test: localStorage.getItem('token'), 
      password: '', 
      errorMessage:'',
      token: '',
      isAlert: false
    }
  },
  computed: {
    loggedIn() {
      return this.$store.getters.isLogged; 
    }, 
    isValid(){
      return this.$store.state.isValid;
    },
    tokenToCheck() {
      return this.$store.state.tokenToCHeck;
    }
  },
  mounted() {
    this.$store.commit('CHECK_TOKEN');
  },

Note: There are no errors showing up in the console, and the secret key used is different than what is mentioned here.

Answer №1

To ensure the commit is triggered appropriately, it should be initiated by a method or within a life cycle hook. It is recommended to retrieve the store state using computed properties. Within the component script, include:

computed:{
  authenticated() {
      return this.$store.getters.isAuthenticated; 
    },
  isValid(){
    return this.$store.state.isValid
   },
  getTokenToVerify(){
     return  this.$store.state.tokenToVerify
  }
},

mounted(){
this.$store.commit('VERIFY_TOKEN') 
}

The template structure will appear as follows:

<p>Current token : {{ getTokenToVerify }}</p>
<p>{{isValid }}</p>
<p>{{ authenticated }}</p>

<div class="alert alert-success" v-if="authenticated"><p>You are logged in</p></div>

Answer №2

Hey there! Just wanted to share with you all:

I recently implemented the vue-storage-watcher npm plugin for my project.

Though it seems to be functioning properly, I am definitely open to hearing suggestions from more seasoned developers on alternative methods.

Appreciate your help!

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

Switching hover behavior on dropdown menu for mobile and desktop devices

I have implemented a basic JavaScript function that dynamically changes HTML content based on the width of the browser window. When in mobile view, it removes the attribute data-hover, and when in desktop view, it adds the attribute back. The functionalit ...

Unable to retrieve a particular file from S3 while utilizing Strongloop

While I am able to upload, delete, and list folders from an Amazon S3 container using Strongloop, I am facing difficulties retrieving a specific file. This is my code: $scope.getS3Files = function(myfolderName){ //need to fetch all zip files in myfolderA ...

Tips for attaching a modal generated in an iFrame to the main window using Javascript or JQuery when the domains are different

I'm currently working on a solution to add a modal from an iFrame into its parent container, even though they are on different domains and violating cross-origin policies. After successfully adjusting the iFrame height using postMessage() in JavaScri ...

What is causing my program to invoke axios twice?

Struggling with setting profile state using redux and encountering the issue of axios being called twice for some reason. Here is my database profile.js: const mongoose = require("mongoose"); const Schema = mongoose.Schema; // Create Schema const Profil ...

Steps for deploying Nuxt on a subdirectory using either Express JS or Plesk

I have configured my Nuxt (Node.js application) to run on Plesk. This means that Plesk will execute the server.js file, which in turn runs ExpressJS and then Nuxt. Here is the content of my server.js file: const express = require('express') cons ...

Guide on converting a unique JSON structure into a JavaScript object

I've been on the hunt for a solution to this unique format challenge, but have hit a dead end so far. The issue at hand is that I'm dealing with a JSON format that doesn't play nicely with mongoDB. My goal is to convert the JSON data into a ...

I am having difficulty getting the correct totals to display on the event list

I have a list of events that are displayed under the dates they occur, but I want them to show as "Today + the date" or "Yesterday = the date" depending on whether it is true or not. $notes = UsersNote::where('user_id','=',$user_id ...

How to effectively combine css() and delay() in jQuery?

fid: https://jsfiddle.net/k13sazuz/ Is there a way to create a delay chain for CSS rules using jQuery? $('.two').css('background','blue').delay(11800).css('background','red'); ...

Combine arrays if the objects inside them are identical

Is anyone online? I need help. I have an array structured like this. var array = [ { roomNumber: 'R01', roomType: 'Deluxe', basic_facilities: 'Hot Water', additional_facilities: 'Iron' }, { roomNumber: 'R01 ...

Tips for displaying images uploaded by the user in a div using an input field

I have a file input field where users can select a file to upload. I want to use JavaScript to display the selected file after it has been uploaded by the user. How can I accomplish this? Does anyone know how to show the selected file in a file input fiel ...

Issue with updating a React form by re-rendering with a state variable

const [ usernameBox , setUsernameBox ] = useState(false); return( { usernameBox ? <> <div style={{ fontSize:"25px" }}>{"Sign up with Security"}</div> <TileI ...

Explore the jQuery feature that allows you to hover over text

I'm facing an issue that has got me a bit stuck on how to resolve it. Currently, when hovering over this specific image, the opacity decreases (exposing a background color) and text appears. However, I want this effect to persist even when hovering o ...

Include a variety of links in an unordered list, with only the initial link triggering a click event

When presenting the user with a choice between two links, I want them to be able to select either one and have it navigate to the corresponding destination. However, in my current setup, no matter which line they click on, it always redirects to the first ...

Guide to: Implementing Radio Buttons to Adjust Image Opacity

How can I dynamically change the opacity of an image using JavaScript when a radio button is clicked? I attempted to achieve this using a forEach function, but the current code causes all images to instantly switch to opacity 1; Additionally, after refre ...

Getting a 401 error when using the Companies House API with jQuery and ajax

I attempted to retrieve JSON data from the UK Companies House API but encountered a 401 error An error occurred: the server responded with a status of 401 (Unauthorized) I implemented jQuery with the ajax() method for this task, and here is a snippet o ...

Adding Tooltips to Your Bootstrap 5 Floating Labels Form: A Step-by-Step Guide

Can you include tooltips or popovers in Bootstrap 5 floating labels text? I've set up a form with floating form fields and I'd like to provide instructions for certain fields using tooltips or popovers. I can make it work with the standard form ...

Using multiple static asset directories in express

Utilizing express, I am aiming to serve static data to my application and manage requests to a protected API. Consider the following folder structure: root/ node_modules/ dist/ app/ server/ app.js // Main server file. src/ app/ ...

Guidelines for Sorting Objects and Arrays in a JavaScript Array

I have a set of data that needs to be filtered based on specific parameters. While I can successfully filter through the initial value in the array, I am struggling to filter deeper into nested arrays. The dataset is structured as follows: let data = [ ...

The slider on my iPad and Kindle Fire in Linux mode is not functioning properly

Having an issue on my e-commerce platform, Bence Tupperware, which is built with MVC.Net. The problem seems to be related to the slider at the top of the page. After checking in Mozilla's responsive design mode, everything appears to work fine on devi ...

Prevent the Rain from descending

Looking for a way to toggle a particle emitter on or off, I've encountered memory leaks with my Reactjs code that generates rain/snow particles using the canvas element. Despite attempts to stop the animation properly, it seems to be projecting a new ...