Troubleshooting problems with VueJS routing

Currently, I am expanding my skills with VueJS by working on a user login system.

My main goal is to prevent a logged-in user from accessing the login or register pages and instead redirect them to the dashboard page.

To achieve this, I am utilizing store.js to manage user data.

In my code snippet within router.js, I made an attempt to implement this logic:

    path: '/signin',
    component: SigninPage,
    beforeRouteEnter(to, from, next) {
      console.log(store.state.userId)

      if (store.state.userId) {
        next('/dashboard')
      } else {
        next()
      }
    }
  }

Despite importing store.js, I encountered an issue where the store.state.userId always returns null when accessed in the router even though it correctly displays the userId in my views when the user is authenticated.

Upon further investigation, I confirmed that the store.state holds the necessary data when logging it in the router.js.

Screenshot of the store state object in the console log

However, I am puzzled as to why the userId key remains unresolved and shows up as null. This discrepancy has left me confused and seeking clarification on the blocking issue.

If anyone can shed some light on where I might be going wrong with my implementation, it would be greatly appreciated as I seem unable to grasp the root cause despite various attempts.

Answer №1

beforeRouteEnter serves as an in-component guard that should reside within the component itself, rather than the registered route. It's puzzling how it still manages to produce output in your application despite not being explicitly called.

If you're looking to define logic within the router, consider using beforeEnter(to, from, next) instead.

For a more comprehensive understanding, refer to the official documentation: https://router.vuejs.org/guide/advanced/navigation-guards.html#per-route-guard https://router.vuejs.org/guide/advanced/navigation-guards.html#in-component-guards

UPDATE: Upon further investigation, I've identified the issue related to the delayed loading of state in the router JS. To mitigate this, I recommend incorporating the logic within the created function of app.vue.

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

Sliding the container with a width adjustment and left margin fails to display all images

In the provided HTML code below, there is a functionality to move images horizontally by clicking on buttons: $(document).ready(function() { calculate_width(); $('#moveleft').click(function() { var loga = $('#marki #loga'); ...

Generate event listeners for buttons dynamically using a string without causing any conflicts

In my current project, I am using a for loop to dynamically populate an HTML table with values from an array. Each row in the table includes a button that needs to link to a different URL. thisbutton.addEventListener("click", function(){ window.l ...

Apply a specific CSS class to a division depending on the currently active cookie

I have implemented cookies on specific pages using https://github.com/carhartl/jquery-cookie. Could someone guide me on how to apply a CSS class to an ID (e.g., adding class .red to #mouse if the cookie named "socks" is active)? For example: If there is ...

What is the process of declaring state in React components?

I have recently started learning React and I am curious about how this code snippet should function: class App extends Component { > 4 | state = { | ^ 5 | bands: [], 6 | concerts: [] 7 | } Below is the error message being ...

Tips for navigating a list of areas in JavaScript

Currently, I am in the process of learning Javascript and I have a query regarding browsing an area list using Javascript. Could someone kindly guide me on whether it is possible to achieve this, and if so, how? Below is the HTML code snippet I am workin ...

Creating a single loop in Javascript to populate two dropdown menus with options

Is there a way to populate two dropdown menus in JavaScript with numbers using the same for loop? Currently, only one is being populated, specifically the last one. for (var i=1; i<10; i++) { var option = document.createElement("option"); option. ...

Using various Content-Types within a single path with Serverless Next JS

Is it possible to achieve the following scenario using serverless on Vercel with Next JS? I have a route /product/[id].tsx. When a request is sent with the header Accept: text/html, I want it to follow the normal Next JS flow and display a React page. How ...

Switch back and forth between two tabs positioned vertically on a webpage without affecting any other elements of the page

I've been tasked with creating two toggle tabs/buttons in a single column on a website where visitors can switch between them without affecting the page's other elements. The goal is to emulate the style of the Personal and Business tabs found on ...

Incorporate AJAX into your Javascript code for ordering

My issue arises when pointOnMap() is executed before xmlPreparer(), even though they are called in the correct order. I suspect this has something to do with the use of AJAX, as parseXML creates the object that pointOnMap() requires to be initialized befor ...

Steps for automatically toggling a button within a button-group when the page is loaded using jQuery in Bootstrap 3

Here is a button group setup: <div class="btn-group" data-toggle="buttons"> <label class="btn btn-default"> <input type="radio" name="environment" id="staging" value="staging" />Staging </label> <label class= ...

Show and hide a division based on the status of a checkbox

I have a specific requirement regarding authentication modes. When selecting a single factor, only one type of authentication mode can be chosen at a time and the corresponding div will be displayed. However, when selecting multiple factors, I should be ab ...

Do class bindings with variables need to be inline when using Vue 3?

Consider the following HTML: <template v-for="(child, index) in group"> <div :class="{'border-pink-700 bg-gray-100 ': selected === child.id}"> <div>Container Content</div> </div> & ...

The ValidationEngine fails to validate a dynamically generated form

After dynamically creating a form, the validationEngine stops working. $(window).load(function($) { var form = document.createElement('form'); form.setAttribute('id', 'xform'); var lbl_usr = do ...

Access my account on the one.com control panel using the identical login credentials

I am curious if it's possible to implement a login page on my website for customers and then seamlessly redirect them to the control panel on one.com without requiring them to re-enter their username and password? Visit the action page on one.com her ...

How can nunjucks templates be accessed from NPM (node modules)?

Is there a solution to make nunjucks imports/includes resolve from the NPM node_modules directory? Let's say we have installed a package as follows: npm i -S @example/cards Now, we need to import from it in a template like this: {% import "@exampl ...

Are there any resources available for OAuth registration within the .NET framework?

Hello everyone! I am looking to add OAuth registration to my project, but I don't have the time to learn the entire protocol and write code from scratch. Does anyone know of a .NET library that can simplify the process for me? I'm specifically in ...

The array element is not being shown in the id "main" when using a for loop with the onchange function

I've been using document.write to display specific content, but it seems to be removing other elements from the page. Is there a way for me to display this loop inside the element with id="main" without losing any content? When I attempt to use docume ...

Issue: Incorrectly calling a hook. Hooks can only be used within the body of a function component. Assistance needed to resolve this issue

import React, { useState } from "react"; const RegistrationForm = () => { const [name, setName] = useState(""); const [password, setPassword] = useState(""); const [email, setEmail] = useState(" ...

techniques for presenting tabular data in a JavaScript modal

Hey there! I'm looking for a way to show table formatted data in a JavaScript popup. Do you know if it's possible to display table formatted data in a JavaScript popup using ASP.NET and C#? ...

Ways to verify if navigateTo has been called in Nuxt.js

I am currently developing a project with Nuxt.js and using Vitest for unit testing. In my tests, I need to confirm whether the navigateTo function from Nuxt.js is being called with a specific path. Below is the relevant part of my component (Form.vue) whe ...