The Vue user object appears to be null in spite of being defined and clearly visible in the log output

There seems to be an issue with my function that utilizes a person's user name to retrieve the current User from the database. Initially, when I log the current user within the function, everything works perfectly. However, once I attempt to access it afterwards, it either shows as null or undefined.

Within my mounted method:

mounted() {
    this.getCurrentUser(this.currentUserName);
    console.log(this.currentUser)

  }

Here is the code for getCurrentUser():

getCurrentUser(currentUserName){
        UserDataService.getCurrentUser(currentUserName)
            .then(response => {
               this.currentUser = response.data;
               console.log(this.currentUser);
            })
              .catch(e => {
              console.log(e);
            });
    }

In my UserDataService class:

getCurrentUser(userName){
        return http.get("/users?userName="+userName);
     }

You can see a screenshot of when it is logged inside the getCurrentUser function here

However, outside of the function, it appears as null whenever I log it in mounted().

Answer №1

When you make an asynchronous call, the result of executing getCurrentUser may not be immediately available.

In the method, it waits for the log to complete, but in the mounted section, there is no waiting.

To address this issue, you can make the mounted section asynchronous and wait for the result, though keep in mind that you will have an empty component in the meantime.

async mounted() {
    await this.getCurrentUser(this.currentUserName);
    console.log(this.currentUser)
}

Additionally, remember to return the promise from the getCurrentUser function.

getCurrentUser(currentUserName){
   return UserDataService.getCurrentUser(currentUserName)

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

Step-by-step guide on making a post request to the Facebook Graph Api with Httparty in a Rails application

I'm currently working on developing a bot for Facebook Messenger, and I need to make a post request call to the Facebook Graph API. The sample code provided by Facebook is in Node.js, but I am working with Rails as my backend framework. Sample Code ...

Angular 4 applications do not come with TinyMCE embedded

I've been attempting to integrate the tinyMCE editor into an angular4 application, but unfortunately I encountered an error that reads: tinyMCE is not defined. https://i.stack.imgur.com/qMb5K.png I have been following the guidance provided by tin ...

difficulty updating data values with $emit on a Vue object

Utilizing $emit to facilitate communication between a child and parent component. A method in the child component triggers the $emit at different stages of an api call. For instance, before initiating the api call, certain values need to be sent to the par ...

What is preventing the data property from updating in setInterval?

Looking for a way to increase the speed of the props while my marker is moving? Currently, the speed only updates when the pause button is clicked. How can I automatically update this.speed when clicking the speed button? I have defined the speed prop in ...

How to achieve rounded corners on cards in Vue.js using Vuetify?

I'm attempting to achieve rounded corners on a v-card, similar to what I can do with a btn. However, it doesn't seem possible? Here is the code snippet I used: <v-card round class="elevation-0"> Below is my template: <template> ...

Using VueJS components, learn how to implement a table with data rows sourced from a subcomponent

I am facing an issue with the alignment of data headers and rows in a scenario where the data is fetched from a separate subcomponent. The headers are displayed along with the data, but they do not align properly with the respective rows below them. Below ...

Issues with Javascript code syntax

I have encountered an issue while creating a new literal control from code behind. I am able to add standard HTML into it successfully, however, when I try to insert <%= SomeDiv.ClientID %> into the literal control, it simply prints exactly what is i ...

"Two vibrant hues in a showdown for dominance over a single pixel on the screen in

When using this Three.js application (), the issue arises where the black wireframe competes with the yellow solid, causing pixel flickering on the screen. Is there a way to prevent this from happening? It's worth noting that the flickering effect is ...

Observing rxjs Observable - loop through the results and exit when a certain condition is met / encountering an issue with reading property 'subscribe' of an undefined value

I'm fairly new to working with rxjs and I've been struggling to find the right operator for what I want to achieve. Here's my scenario - I have an array that needs to be populated with results from another observable. Once this array has en ...

Is it possible for me to take action on and then pass along the outcomes of an AngularJS $http request without relying on $q?

I have a function called getData that retrieves data from an API endpoint. My current implementation utilizes $q to handle promises. After processing the retrieved data, I return another promise: var getData = function (controller) { var defer = $q.d ...

The reason why setting height to 0 is ineffective in a CSS definition

Within my current project, I am utilizing vue.js 2 and have implemented an img component. Below is the code for this component: <template> <div class="banner"> <img class="banner-img" :src="bannerImg"/> </div> </template> ...

Instructions on incorporating a logical condition for an object that is entering a region in motion

I am currently in the process of developing a new game concept. The goal of the game is to maneuver a square across the screen while avoiding raindrops that fall from the top of the canvas. I need assistance with programming the logic so that when a rain ...

What is the best way to incorporate a line into a scene using three.js?

I am facing an issue with adding a line in three.js. When I call the addline function in my code, the line doesn't appear in the scene. I have tried to implement the MVC design pattern, but I am unsure where I went wrong. Thank you for any assistance ...

Error with infiniteCarousel in Internet Explorer versions 7 and 8 when using jQuery

Hello everyone! I've run into a little issue with some jQuery code I'm using. It was working fine before, but after making several changes and improvements, I can't seem to figure out what the problem is. I keep getting JS errors in both IE7 ...

React and Spring are encountering an issue with cors error when attempting to send a post request due to the response to the preflight request not passing the access control check

Attempting to authenticate a user on my spring-boot backend from a react frontend has been challenging due to an error I keep encountering. The error message states: Access to XMLHttpRequest at 'http://localhost:8080/auth/authenticate' from orig ...

unusual behavior of UTF-8 characters in Blogger when utilizing JavaScript

I'm facing a peculiar issue with JavaScript in my Blogger code when dealing with certain characters like '¡' and '?'. For instance, the following code snippet displays ñéúüëò¡!¿? inside the div but shows ñéúüëò&# ...

Flashing Effect of Angular Ui-Bootstrap Collapse During Page Initialization

Below is the code snippet I've implemented to use the ui-bootstrap collapse directive in my Angular application. HTML: <div ng-controller="frequencyCtrl" style="margin-top:10px"> <button class="btn btn-default" ng-click="isCollapsed = ...

Can I safely keep a JWT in localStorage while using ReactJS?

As I work on developing a single page application with ReactJS, one question comes to mind. I came across information indicating that using localStorage may pose security risks due to XSS vulnerabilities. However, given that React escapes all user input, ...

Setting the cache to false during an httpget request in an mvc4 controller action: tips and tricks

My httpget request to a controller action looks like this: $.get('/Course/ExplanationCorrect/', postData, function (data) { $('#SurveyDiv').html(data); }); While it works on all other browsers, I'm facing an issue with IE10 o ...

Need assistance with a coin flip using HTML and Javascript?

After spending hours trying to make the code work with the example provided, I find myself unable to get it functioning correctly. Is there anyone who can assist me in putting all of this together so that it runs smoothly? var result,userchoice; functio ...