Using Laravel and Vue to initialize authentication from the store prior to rendering any components

I'm currently immersed in a project that involves Laravel and Vue.

My Objective I aim to authenticate a User before displaying any Vue Component to show the username in the Navbar.

Challenge The issue I'm facing is that the Vue Navbar Component gets rendered before the user authentication process completes, resulting in the navbar not displaying the username due to the component not being updated.

Query How can I access the store, trigger a mutation (user authentication) before creating the new "Vue" with components? Or, how can I ensure reactivity so that the component updates as soon as authentication is successful?

I also attempted using "computed" to update the state and username after the store.state.user changes. However, this approach doesn't seem to work possibly because of my limited understanding of reactivity despite reading extensively on the topic.

Additional Information Below are some key background details:

  • I utilize Laravel for setting up routes (both Frontend and Backend)
  • The use of a layout.blade file and inclusion of Vue components in the designated Laravel view files
  • Authentication through JWT (working effectively)

Here's a snippet from my layout.blade.php

<!doctype html>
<html>

<head>

    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="csrf-token" content="{{ csrf_token() }}">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <title>Gembox</title>
        <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700,400italic|Material+Icons">
        <link rel="stylesheet" href="https://unpkg.com/vue-material/dist/vue-material.min.css">
        <link rel="stylesheet" href="https://unpkg.com/vue-material/dist/theme/default.css">
        <link rel="stylesheet" href="{{asset(mix('/css/app.css'))}}">
    </head>
</head>

<body>
    <div id="app">

        <header>
            <div>
                @include('includes.header')
            </div>
        </header>
        <div class=" main-container md-elevation-4 container">
            @yield('content')
        </div>
        <footer class=" md-elevation-4 mb-1">
            @include('includes.footer')
        </footer>
        <script src="{{asset ('js/app.js')}}">
        </script>
        <script src="https://unpkg.com/vue"></script>
        <script src="https://unpkg.com/vue-material"></script>
    </div>
</body>

Your assistance is greatly valued!

Warm regards, Jörg

Answer №1

After reviewing your code, I noticed a couple of issues that need to be addressed:

Remember, Vuex Mutations are synchronous while Actions are asynchronous

Reference: Vuex Documentation on actions

It's important to place your business logic in actions since they handle asynchronous tasks like axios calls, while mutations should be used for data update/manipulation.

In the "AUTH_USER" mutation, an axios call is being made which should actually be moved to the "authUser" action instead.

\\ Your SET_USER mutation can be updated as shown below 

SET_USER(state, payload) {

  \\ User data will be passed as the second parameter (payload) 
  state.user = payload

  \\ Set the loggedin variable to true if we receive data in the payload, otherwise set it to false
  state.loggedin = (payload) ? true : false

}

\\ Your authUser vuex action can be modified as follows, returning a promise 
authUser: ({ commit }) => {
   return axios
     .get("api/register", {
        headers: {
          Authorization: `Bearer ${localStorage.usertoken}`
        }
      })
      .then((response) => {
        commit("SET_USER", response.data.user);                
      })
      .catch((err) => {
        console.log(err, "Could not retrieve data");
      });

}

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

Tips for efficiently resolving and compiling a bug within an NPM package, ensuring it is accessible to the build server

This question may seem a bit unconventional. I am currently using an npm package that includes built-in type definitions for TypeScript. However, I have discovered a bug in these definitions that I am able to easily fix. My goal is to make this updated ve ...

Possible rewrite: "Unable to use jQuery to add elements to data fetched through AJAX requests."

I am looking to add a button to copy code inside every div that has a class starting with language. The code is functioning properly, however, after attempting to retrieve data from the database using Ajax, the button no longer appears in the div as it did ...

What could be the reason for PhantomJS getting stuck when jQuery is invoked?

Currently, I am using PhantomJS 2.0.0 on a Mac OS X Yosemite: $ phantomjs --version 2.0.0 The script I have attached below seems to get stuck at the line where it calls $('h1').size(): system = require('system'); function usage() { ...

Using webGL for rendering drawElements

I am working with face-indices that point to specific points to draw triangles in a loop. Unfortunately, when executing my code, I encountered the following error in the web console: WebGL: drawElements: bound element array buffer is too small for given c ...

Store data in Laravel's storage directory

I encountered an issue while trying to save files to the storage folder in Laravel after deploying the project on a web server (byethost7.com). The files were only being stored in the public folder. I ran the following command in the command prompt: >p ...

Refresh the angular list filter by clicking on it

I'm struggling with updating an Angular list after the filter is changed. Below is the HTML code I am using: <li ng-repeat="items in list | filter:filterList" style="list-style-type:none"> {{items}} </li> Additionally, here is the o ...

What is the correct way to utilize the Vuex mutation payload object effectively?

I have two input fields where I can enter a value to search for either the name of a company or the location. The search functionality works when only one argument is provided in the foundJobs mutation and action. However, when the payload contains an obje ...

How can you use the MongoDB Aggregation Framework to filter by a range of dates, group results by individual days, and calculate the average value for each day

I'm currently exploring the possibilities of MongoDB's Aggregation Framework and would appreciate some assistance in enhancing this query to achieve the following objectives: Retrieve Records with Dates falling within a specified range Organize ...

Navigating through nested promises can be a daunting task within the world of JavaScript and Angular

Function 2 relies on the return of Function 1, while Function 3 uses both returns. How can I clean up this process? Currently, Function 3 is only giving me undefined values. Below are my 3 functions: Function1 $scope.nombreCompetencesATraiter = function ...

Securing Laravel AJAX calls with CORS and CSRF Tokens

Is there a way to provide a CSRF token for cross-domain (subdomain) requests in Laravel? Both the domains domain.tld and sub.domain.tld are operating under the same Laravel Framework. Although I can use csrf_token() in sub.domain.tld and directly attach ...

What are the steps to retrieving information in Vue 3?

I'm encountering an issue with fetching data using Vue 3. I've set up an action to call an endpoint (), but I'm not receiving any response data. The defined endpoint is as follows: import { createStore } from 'vuex' export d ...

Replace the icon in Material UI Stepper for steps that have errors

I am utilizing Material UI's Stepper component to display a checklist in this manner. The image below is from their documentation. https://i.sstatic.net/KfUos.png While attempting to add an error state to the checklist, I discovered a prop called er ...

Performing various calculations using a v-for loop to determine multiple totals

I have a unique scenario where I am using nested v-for loops in Vue to display information about users and their accumulated leave. Here is a simplified version of what I am trying to achieve: v-for user in users //Display user's name v-for ...

Reorganizing JSON Information

Currently, I am dealing with a JSON file that contains multiple sets of data structured like this: {"name": ["Adelphi University"], "supp": ["Yes: E, WS"], "ed": ["\u00a0"], "online": ["$40"], "ea": ["12/1"], "mid": ["No"], "rd": ["Rolling"], "recs": ...

endless cycle of scrolling for div tags

My goal is to incorporate a tweet scroller on I believe it uses the tweet-scroller from Unfortunately, this link seems broken as the demo is not functioning. I searched for an alternative solution and came across http://jsfiddle.net/doktormolle/4c5tt/ ...

Tips for utilizing a 'v-for' directive with objects within a blade element in Vue.js

I am currently working on a code that includes a loop within which there is an <a> tag. I aim to generate the link for this tag using a server-side code function. An excerpt from my code is as follows: <div v-for="file in file ...

Error 429 encountered in Laravel when accessing /oauth/token

It seems that I keep getting a 429 error every time I attempt to connect to my API server. I have even gone as far as commenting out the throttle from Kernel.php, but the issue persists. ...

Is there a way to efficiently access checkboxes by their IDs and toggle classes without the need for redundant classes and functions?

In my current project, I have set up functionality to toggle classes on a table for hiding specific columns. This is determined by checkboxes selected by the user above the table, each checkbox having its own unique ID like "product_1", "product_2", and so ...

There are a total of 152 issues found in the index.tsx file within the react

Despite everything working correctly, I am continuously encountering these errors. Is this a common occurrence? What steps can I take to resolve them? I have developed my react application using Javascript instead of Typescript; however, I don't belie ...

Determine the height of a DIV element and its contents using JQuery

In this div, there are various elements present: <div class="menuItem designMenu" id="dMenu"> <ul class="menuList menu"> <li class="menuHeader">Design</li> <li class="projectHeader">Mother</li> <li clas ...