LWC user id undefined

lightning-web-components

I am developing a lightning component with LWC. In order to get the contact associated to the current connected user, I am getting the user id using this line of code :

import currentUserId from '@salesforce/user/Id';

The import does not show any issue, but when I try to access the value of the property it seems to be 'undefined' even if I am using the component in a connected Salesforce environnement.

An example of the code used the property below

In the connected callback method :

  connectedCallback(){
     if(this.currentUserId){
         console.log('user id');
         console.log(this.currentUserId);
         this.currentConsultant = getContactFromUser(this.currentUserId);
         console.log('current consultant');
         console.log(this.currentConsultant);
         this.isGlobalView = (this.currentConsultant==null && (this.currentConsultant=== undefined))
     }  ...

//in rendered callback method

   renderedCallback() {
     console.log('rendered');
     console.log(this.currentUserId);
     
 }

Thank you in advance.
Have a great day.

Best Answer

Imported properties are like constants in LWC or ES6 in general, they can be accessed directly and does not need a this keyword.

Either you can use the property directly currentUserId without this:

import currentUserId from '@salesforce/user/Id';
console.log(currentUserId);

or

Define a local property, then you can use access the record id via this keyword:

import { LightningElement } from 'lwc';
import Id from '@salesforce/user/Id';

export default class ExampleGetUserId extends LightningElement {
    currentUserId = Id;
    connectedCallback() {
        if (this.currentUserId) {
            console.log("user id");
            console.log(this.currentUserId);
        }
    }
    renderedCallback() {
        console.log("rendered");
        console.log(this.currentUserId);
    }
}