How to use getRecord in LWC
When we have to fetch a single record from the database we don't have to do the song and dance of writing custom logic (using apex code) to fetch the record.
In this post, we will be looking at how to use getRecord()
in LWC and fetch a single record.
When we have to fetch a single record from the database we don't have to do the song and dance of writing custom logic (using apex code) to fetch the record.
We can use the out-of-the-box methods (getRecord in this case) that Lightning Platform provides via LDS (Lightning Data Service) module.
Here are the series of steps that we need to implement to see that it works.
- Import the named imports
getRecord()
andgetFieldValue()
from the packagelightning/uiRecordApi
. - Import the reference to the fields that we wish to display back to the users.
- Wire the output of the out-of-the-box method
getRecord()
to the property account. - Fetch the field values from the record using the method that we imported in step 1 i.e
getFieldValue()
It's a mandate that we provide the "recordId" in quotes and append a $ symbol in front of it. Because when the content of recordId
is changed the apex method will be invoked again and the modified return value will be assigned back to the prop account
.
This is how the template file is going to look like
Hope this was helpful!
I have put together a FREE course on Javascript that helps you master Lightning Web Components.
It just takes 2 hours to finish the course and you will be able to feel the difference.