0

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?

1 Answer 1

3

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;
}

You must log in to answer this question.