Wire Service Considerations when using LWC and Flow

Wire services fire initially before any flow data is loaded into an lwc’s public properties. If you’re using flow inputs to drive those wire services, like this:

import getObjectApiName from '@salesforce/apex/AddChildObjectToConfigController.getObjectApiName';
 
export default class AddChildObject extends LightningElement {
    @api recordId;
    @api objectApiName;
    error;
 
    @wire(getObjectApiName,{recordId:'$recordId'})  //the first time this fires, recordId will be undefined
    initializeObjectApiName

…keep in mind that your function will have to deal with that initial result that comes back, which will often be something like undefined. What you want to watch out for is throwing an error message instead of just letting that first firing quietly sink. For example, this code will always stop processing with an error message:

        @wire(getPicklistValues, {
		recordTypeId: "$recordTypeId",
		fieldApiName: "$objectAndFieldName"
		//fieldApiName: "$calculatedObjectAndFieldName"
	})
	picklistValues({ error, data }) {
		if (data) {
			...do useful stuff
			}
		} else if (error) {
			throw new Error("something went wrong with the request to get picklist Values!");
		}

In the normal course of action, wire services like the one above will fire a second time once the flow values have arrived.

It can be useful to make use of getters to provide finer grain control. Here’s an example:

import { LightningElement, wire, api } from 'lwc';
import { getPicklistValues } from 'lightning/uiObjectInfoApi';
 
export default class Example extends LightningElement {
    @api rtId;
    @api objectApiName; // string eg 'Account'
    @api fieldApiName; // string eg 'Type' 
    @wire(getPicklistValues, {
        recordTypeId: '$rtId',
        fieldApiName: '$calculatedFieldApiName'
    })
    picklistValues;
 
    get calculatedFieldApiName() {
        if (isString(this.objectApiName) && isString(this.fieldApiName)) {
            return `${this.objectApiName}.${this.fieldApiName}`;
        }
        return undefined;
    }
}
 
function isString(value) {
    return typeof value === 'string';
}

In the example above, the code ultimately has to concatenate two strings into a single combined string and provide that to the getPicklistValues wire service. When the wire service first fires though, and both of those initial strings are undefined, the concatenation attempt will fail spectacularly. The getter above ensures that if the data is not present, a simple undefined will be passed to the wire service.

More information on adding LWC’s to Flow Screens

Subscribe
Notify of
guest
1 Comment
Inline Feedbacks
View all comments

[…] It can be a little tricky to get wire services interacting properly with incoming flow data. Details here. […]