Posted in Salesforce

Salesforce Lightning : A better way to handle component.find return value

I have always seen Salesforce Aura Component developers using multiple checks before fetching data from component.find method. It is because, it does return three types of results:

  1. undefined – when there are no items found on the DOM
  2. Single component – when there are only one item found in the DOM
  3. Array of components – when there are more than an item found in the DOM

It is always painful to check first if the component.find returns a value, followed by a second condition to check if the return value has an attribute length to fetch values using an iterator before finally get the element directly. Missing any of these steps will be a nightmare for the application.

To simplify this process, there comes a Javascript method for a rescue – concat

var elements = [];
elements = elements.concat(component.find('mySearchElements'));

Now, this ensures that your elements variable is always an array, be it 0 search elements or 1 or more search elements, you can just check if the array has elements or not.

This way, would even helpful while using reduce method, where we mostly use to check the validity of the form. It can be even as simpler as this:

[].concat(component.find('myFormElements')).reduce(function(validSoFar, inputCmp) {
      //...
}, true);

One thought on “Salesforce Lightning : A better way to handle component.find return value

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s