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?

2

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;
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.