How to call @wire(getRecord) from an event handler

lightning-data-servicelightning-web-components

I'm creating an LWC component for Flow which contains a pill container of "recipients", and a lookup field to add recipients.

I'm using lightning-record-edit-form and onsubmit to call a handler function which prevents the creation of a record, and gets the Id of the record which was selected in the lookup field.

I want to pass this recordId to the getRecord function and return the name of the record (or some other field), and use the Name and Id to populate the array of pill items.

I'm not quite sure of the syntax to achieve this, and what I've tried so far is the below, but I'm getting an error which prevents the component from rendering (which seems right as I assume the getRecord function is executed on render):

import { LightningElement, api, track, wire } from "lwc";
import { getRecord } from 'lightning/uiRecordApi';

export default class PillMultiSelect extends LightningElement {
  @api lookupField;
  @api sourceObjectApiName;
  @api fieldForPill;
  @track items = [];

  recordIdFromLookup;

  handleAddToList(e) {
    e.preventDefault();
    e.stopPropagation();

    this.recordIdFromLookup = e.details.fields[this.lookupField];
  }

  @wire(getRecord, { recordId: $recordIdFromLookup, fields: this.fieldForPill})
  addPill( {error, data} ) {
    if (error) {
      //some code
    } else if (data) {
      const pillRecord = data
      this.items.push({
        label: pillRecord.fields[fieldForPill],
        name: this.recordIdFromLookup
      })
    }
  }

I suppose I could set an initial record Id on recordIdFromLookup? But if anyone has any idea on how to achieve what I'm trying to do, ideally without using Apex, that would be much appreciated.

Best Answer

The API property, fieldForPill should be an array if you are using it in getRecord. Are you passing it in as an array? If you don't want to change it to an array, you can set a new property in a connectedCallback()

// New property
fields;
connectedCallback() {
    this.fields = [this.fieldForPill];
}
// Update wire method
@wire(getRecord, { recordId: $recordIdFromLookup, fields: fields})
addPill( {error, data} ) {
    if (error) {
    //some code
    } else if (data) {
        const pillRecord = data
        this.items.push({
            label: pillRecord.fields[fieldForPill],
            name: this.recordIdFromLookup
        })
    }
}

The wire function is reactive, so when you set the recordIdFromLookup property value, wire will trigger.

Related Topic