Get Record Data

Let’s use the wire service to get record data and display some field names.

This example uses the wireGetRecordDynamicContact component in the github.com/trailheadapps/lwc-recipes repo. This component uses a dynamic schema—it doesn’t import references to fields. For an example that uses a static schema, see wireGetRecordStaticContact in the lwc-recipes repo.

This component renders a custom UI for a contact. To get the data, the component uses the getRecord wire adapter.

Component UI showing record ID and record name.

If the wire service provisions data, the template renders the name, title, phone, and email. If the wire service provisions an error, the template renders the c-error-panel component.

Now let’s look at the component’s JavaScript.

First, the code imports the getRecord wire adapter from the lightning/uiRecordApi module, which is built on Lightning Data Service. Then it defines the fields to pass to the wire adapter.

The component uses @api to define a public recordId property. If the component is nested in a Lightning record page, which our component is, the Lightning page sets the value of recordId.

The @wire decorator tells getRecord to get the values of the specified fields on the record with the specified $recordId. The $ means that the value is passed dynamically. When the value changes, the wire service provisions data and the component rerenders.

The data is provisioned to the data and error objects of the property decorated with @wire. In this example, that’s the contact property.

Since the default value for data that's returned by the property is undefined, this example depends on the lwc:if directive to check if contact.data has been populated with the contact record. The getters in your JavaScript code are called when contact.data has been populated with the contact record. Alternatively, use getFieldValue(record, field).

Look back at the HTML template. The name, title, phone, and email fields are bound to the JavaScript class using the {} syntax. In JavaScript, each property has a getter function that uses the contact.data object to access the value of its namesake field.

The structure of the returned data is the same as the structure returned by the User Interface API that getRecord is built on. In this case, the response is Record.

This example demonstrates data access via the returned JSON object. To simplify data access, use getFieldValue(record, field).

See Also