[SalesForce] How to pass recordId to a variable in a lightning web component

I am attempting to print out the recordId of an account, using a variable inside a lightning web component. Here is my code so far:

javascript:

import { LightningElement,api } from 'lwc';

export default class HelloWordAccount extends LightningElement {
@api recordId; //returns record id
message = this.recordId; //returns undefined?

}

html:

<template>
<ouput>{recordId}</ouput>
<br/> <br/>
<ouput>{message}</ouput>
</template>

The component is on the account page layout, and prints out the recordid inside of the output tags that reference "recordId". I want to pass the recordId to a variable ("message"), when I pass it to a variable, I get nothing. putting the value in an input tag prints out "undefined". What am I doing wrong?

Best Answer

There are 3 things to be remembered here:

  1. recordId will be loaded after the class has been initialised and the framework knows the record context and so when message = this.recordId; is executed, recordId will be undefined .
  2. After setting the record context, connectedCallback() method is invoked and so you should use this method .
  3. Properties should be declared reactive (api, track & wire) when used in HTML so as to rerender when the value changes.

Below code will work:

@api recordId;
@track message;
connectedCallback() {
    this.message = this.recordId;
}
Related Topic