Upon refreshing the page, Vuex encounters an issue where it is unable to read

My website has a Navbar component that utilizes values from the Vuex store. Prior to entering each route, I trigger a dispatch from Vuex as shown below:

router.beforeEach((to, from, next) => {
   //...
   store.dispatch("updateUserData"); 
   next();
});

Here is my Vuex store:

const actions = {
  updateUserData({ commit }) {
    UserService.getUserData().then(
      (response) => {
        commit("updateUserState", response.data);
      },
      (error) => {}
    )
  },
}

const mutations = {
  updateUserState: function(state, user) {
    state.user = user;
  },
}

const getters = {
  getUser: (state) => {
    return state.user;
  }
}

In addition, my Navbar component includes the following:

  computed: {
    currentUser() {
      return this.$store.getters.getUser;
    }
  },

I use the value retrieved from Vuex like this:

<p style="border-left: 1px solid black" class="navIcon pl-4 py-1">
   {{ currentUser.firstName }} {{ currentUser.lastName }}
</p>

Everything works fine when I first load the page containing the Navbar component. However, upon refreshing the page, I encounter the following error in my console:

vue.esm.js?a026:628 [Vue warn]: Error in render: "TypeError: Cannot read property 'firstName' of null"

found in

---> <Navbar> at src/layouts/Navbar.vue
       <App> at src/App.vue
         <Root>
warn @ vue.esm.js?a026:628
vue.esm.js?a026:1897 TypeError: Cannot read property 'firstName' of null

Can anyone provide guidance on what might be causing this issue? Thank you for your assistance!

Answer №1

It seems like the issue is that your action is executed asynchronously, causing the data to not be available to the getter when rendering your component.

One possible solution is to convert your action into an asynchronous one that returns a promise. Then, you can wait for it to resolve in the beforeEach hook before calling next.

For troubleshooting purposes, consider refreshing your app and inspecting the Vue store. Log the value of the current user in the mounted component, and check for any discrepancies.

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

Storing user and message data with LocalStorage technology

Seeking advice on a straightforward approach to storing user data and messages. My idea is to use unique key values, such as random tokens (Ynjk_nkjSNKJN) for users, and real ids (1,2,3) for messages. Has anyone encountered this issue before? The goal is ...

Issues with login validation in HTML when utilizing JSON and PHP

While creating a login form in HTML using JSON and PHP, I encountered an issue where the if statements in the success function were not working properly. However, the beforeSend and error functions are functioning as expected. Can someone assist me in iden ...

Is there a way to make the embed tag match the size of the div tag?

Is there a way to ensure that the size of the embed tag matches that of the div tag? I am able to adjust the size of the embed tag to match the div tag, but I want to maintain the full resolution of the embed tag (which is used for a webcam). <div st ...

Google Sheets API v4 - Add a Row Above (Not Below)

Is anyone familiar with how to use the insertDimension request to insert a row above existing data? I am having trouble finding documentation on specifying where to add the row within the spreadsheet. The code I have inserts the row at the bottom, and I&ap ...

Tips for displaying a table with a button click

I am struggling to figure out how to embed a table inside a button in order to display the table when the button is clicked and hide it when clicked again. Below is the code I have been working with: function toggleTable(){ document.getElementById ...

A hobby project involving the creation of a webmail app using a combination of PHP

As a beginner in web development, I am eager to tackle a hobby project that will help me learn more about PHP and other web-related technologies. I have been considering creating a simple webmail client, but I'm not sure where to begin. I anticipate ...

How to refresh a specific component or page in Angular without causing the entire page to reload

Is there a way to make the selected file visible without having to reload the entire page? I want to find a cleaner method for displaying the uploaded document. public onFileSelected(event): void { console.log(this.fileId) const file = event.targe ...

What's causing my Bootstrap cards to overlap on smaller screens?

When using 3 bootstrap cards in the following code, they are perfectly displayed side by side on large screens. However, on medium screens, the cards overlap, and on small screens, they completely overlap. I tried adjusting the class="col-lg-4 col-md- ...

Step-by-step guide on writing to a JSON file using Node.js

I am currently developing a Facial Recognition web application using React for the frontend and Node.js for the backend. You can find more information about my project here. So far, I have completed the frontend part where users manually add 128-d descript ...

Can we streamline a generic overloaded function's signature to make it more concise?

I have developed a streamlined Axios wrapper function that integrates zod-parsing and presents a discriminated union for improved error handling. While the implementation successfully maintains the default behavior of Axios to throw errors in certain cas ...

Utilizing AJAX for autocomplete in HTML and inserting it into a page using innerHTML is causing issues with the functionality of forms on the website

As I work on developing my website, I am facing an issue with nesting HTML code generated by a PHP page using Ajax innerHTML. While the PHP-generated page loads successfully, it appears modified compared to how I want it to be uploaded. The main problem li ...

What is the best way to interact with my component in React?

As a newcomer to Reactjs, I have a question regarding my current setup: The components in my project include navComponent.js, stackComponent.js, and nav.js I am trying to pass data from stackComponent.js to navComponent.js so that the nav.js data can be ...

Tips for correctly implementing the next() function within a middleware in a Node.js application

After successfully logging in and generating a bearer token, I attempted to verify the token by organizing the codes for controllers, middlewares, and routes. However, upon verification, I encountered the following error message: Error: Route.post() requir ...

Is it possible to generate an HTML element by utilizing an array of coordinates?

I have a set of 4 x/y coordinates that looks like this: [{x: 10, y: 5}, {x:10, y:15}, {x:20, y:10}, {x:20, y:20}] Is there a way to create an HTML element where each corner matches one of the coordinates in the array? I am aware that this can be done usi ...

Unlocking the potential of nested conditional types in TypeScript

The source of the autogenerated type below stems from a GraphQL query: export type OfferQuery = { __typename?: 'Query' } & { offer: Types.Maybe< { __typename?: 'Offer' } & Pick<Types.Offer, 'id' | 'nam ...

"Regardless of the circumstances, the ionic/angular service.subscribe event

Currently, while developing the login section of my Ionic app, I am encountering an issue with the getTokenAsObservable.subscribe() function. The main problem is that the function checks the token status when it is saved (by clicking the Login button) or ...

Leveraging conditional statements for dynamically computed Vue properties

In the Vue site I'm working on, there is a functional button that changes its state when clicked (from "pause" to "resume" and also changes colors). The button functionality itself works perfectly, but I am facing an issue in aligning it with another ...

How to use a JavaScript function to send a request to views.py in Django

Hey there! I'm looking for guidance on sending a request to a function in views.py within Django. Any help would be much appreciated. Thank you! ...

Utilizing JavaScript and JSON to Retrieve Array Elements by Key Names as Indexes

I'm looking for a way to access elements in an array using unique key names instead of numerical indexes. Specifically, I'm developing a Discord bot where each server has its own settings. When a message is sent on a server, I need to retrieve th ...

The filtering and sorting features of Ng-table do not seem to be working properly when dealing with grouped data

Currently, I am in the process of learning angular.js and have recently started using the ng-table directive. While I have successfully managed to group my data and display it using ng-table, I seem to be facing issues with sorting and filtering the data. ...