Validating and securing Public Properties of Lightning web components

Telegram logo Join our Telegram Channel
Validating and normalizing Public Properties of Lightning web components

In the world of Lightning Web Components (LWC), public properties play a pivotal role in facilitating communication between parent and child components. These properties, inherently reactive, enable seamless data flow within LWC applications.

However, ensuring the integrity of public property values makes it difficult to maintain application stability and user satisfaction. In this article, let us explore the importance of validating public property values in LWC and discuss various techniques to enhance user experience.

Understanding Public Properties

Public properties in Lightning web components serve as conduits for parent-to-child communication, facilitating dynamic data exchange. Leveraging these attributes, developers can create versatile and interactive components that adapt to changing data inputs

Why should you validate Public Property values?

Invalid values assigned to public properties can introduce inconsistencies and errors within LWC applications.

By validating these values, developers can safeguard against potential issues, ensuring smooth functionality and user satisfaction. Let's delve into scenarios where validation becomes crucial:

  1. Shared components utilized by multiple developer teams.
  2. Components with design attributes configurable by admins via the Lightning App Builder.
  3. Global components are distributed via managed packages.
  4. Generic components designed for broad usage across organizations or packages.
  5. Utilization of custom metadata for storing component configurations.
  6. Integration of dynamic components into your application.
  7. Development of custom UI components tailored to specific requirements.

Ways to validate public attributes of LWC

Here are the actions you can take when an invalid value is set to public attributes of LWC.

  1. Log an error on the browser console.
  2. Visualize the component with an error state.
  3. Set fallback value.
  4. Normalize property values
  5. Display toast messages.
  6. Throw an exception from JS
  7. Documentation for Multi-Team usage

If the component is intended to be used by multiple teams, it is important to provide proper documentation so that you can furnish users with the link to the "How to Use" wiki page for the component.

Log an error on the browser console

This is the simplest way to handle the public property misconfigurations. See the below example where the ProductCard Component has a value property. The value property should be of type number. If someone passes down any other data type then this will run into an error.

It's essential to include the name of the component in the console.error log so that developers can easily identify the source of the error.

import { LightningElement, api } from "lwc";

export default class ProductCard extends LightningElement {
    @api productName = "Product Name";
    // number
    _value;
    @api
    get value() {
        return this._value;
    }
    set value(value) {
        if (typeof value === "number") {
            this._value = value;
        } else {
            console.error(
                "ProductCard: Expected value to be a number " + value
            );
        }
    }
}

Visualize Error States

Visual cues are essential for user engagement and understanding. Implementing an error state visualization within the component can help users easily identify when something goes wrong, improving usability and reducing confusion.

Now, let's explore an example illustrating this concept. We'll revisit the ProductCard component discussed in the previous section, but this time with additional logic to handle error states.

We've introduced a new property called hasError . When there's a data type issue with the value property, the hasError property is set to true, indicating a type mismatch.

This hasError property can now be leveraged to visually represent the error state of the component. For instance, specific styles or border colors can be applied to indicate the presence of an error.

import { LightningElement, api } from "lwc";

export default class ProductCard extends LightningElement {
		// new property
    hasError = true;
    @api productName = "Product Name";
    // number
    _value;
    @api
    get value() {
        return this._value;
    }
    set value(value) {
        if (typeof value === "number") {
            this._value = value;
            this.hasError = false;
        } else {
            console.error(
                "ProductCard: Expected value to be a number " + value
            );
            this.hasError = true;
        }
    }
}

Set Fallback Values

Let's consider another example: creating a ProductGrid component, which displays products in a responsive grid, resembling an e-commerce website layout.

The ProductGrid component features a public property products, which exclusively accepts an array value. Therefore, it's important to address scenarios where incorrect data types are passed.

To mitigate this issue, a fallback value of an empty array, denoted by [], is set.

import { LightningElement, api, track } from "lwc";

export default class ProductGrid extends LightningElement {
    // private
    @track _products = [];

    @api
    get products() {
        return this._products;
    }
    set products(value) {
        if (value && Array.isArray(value)) {
            this._products = value;
        } else {
            // set a fallback value
            this._products = [];
            console.error(
                "ProductGrid: Expected products to be an array " + value
            );
        }
    }

    // use this property to show message when no products are available
    get productsAvailable() {
        return this._products.length > 0;
    }
}

Normalize Property Values

The property values are passed from JavaScript and sent as objects. However, when you set the property value in an HTML template, they are treated as strings. Additionally, when dealing with multiple-choice options like variants. For example, the Lightning Button has variant options such as Brand, Destructive, Success, Neutral, etc.

How can we ensure that the data type is handled correctly and that the variant options are set accurately? Well, let us see this with a code example.

Normalize string values

Let us take the Product Grid component example and add property a Out of Stock . This is a Boolean property, but when its value is set from the HTML template of the parent it is treated as a string let us handle that scenario.

import {LightningElement, api, track} from "lwc";

export default class ProductCard extends LightningElement {
    // private
    @track _outOfStock;

    @api
    get outOfStock() {
        return this._outOfStock;
    }
    set outOfStock(value) {
        // if boolean value is passed
        if (typeof value === "boolean") {
            this._outOfStock = value;
        } else {
            // if string or other value is passed
            this._outOfStock = value === "true" || value === "TRUE";
        }
    }
}

Let us see another example for a variant, let us assume that the ProductCard component has three different variants, default, portrail , landscape .

import {LightningElement, api, track} from "lwc";

const VARIANTS = ["default", "portrait", "landscape"];

export default class ProductCard extends LightningElement {
    // private
    @track _variant = "default";

    @api
    get variant() {
        return this._variant;
    }
    set variant(value) {
        // if boolean value is passed
        if (typeof value === "string") {
            // normalize string by converting to lower case.
            // and check provided value is valid.
            let val = value.toLowerCase();
            if (VARIANTS.includes(val)) {
                this._variant = val;
            } else {
                this._variant = "default";
            }
        } else {
            // set default variant
            this._variant = "default";
        }
    }
}

Display Toast Messages

Toast messages provide non-intrusive yet informative feedback to users. Incorporating them when encountering invalid property values can greatly enhance the user experience by promptly notifying users about the issue without disrupting their workflow.

Note: Showing too many toast messages can be bad for user experiences, use the toast message carefully for this purpose.

Throw an Exception from JS

Note: This technique is useful for developers perspective and not for end users.

Optionally you can throw a JS exception when a bad value is encountered. This technique should be used only for the utility components exposed only to developers and should have the option to suppress the exceptions from the end users.

While throwing exceptions from JavaScript can be a powerful technique for handling errors, it's essential to consider the user experience implications. Unhandled exceptions can disrupt the application flow and leave users puzzled. If using exceptions, ensure they are caught and handled appropriately to provide meaningful feedback to users

Documentation for Multi-Team Usage

Note: This technique is useful for developers' perspective and not for end users.

You can provide the documentation links in the browser console along with the error message, that is helpful for developers to understand the functionality of the component and its properties.

Providing users with "How to use" wiki page links or documentation links ensures that developers understand the proper usage of the component, reducing errors and promoting consistency across teams.

Conclusion

Validating public property values is integral to building robust and user-friendly Lightning Web Components. By adopting effective validation techniques and prioritizing user experience, developers can enhance application stability, minimize errors, and foster positive interactions with users.

Embracing a proactive approach to validation ensures seamless functionality and reinforces the value of Lightning Web Components in modern web development landscapes.

No comments :
Post a Comment

Hi there, comments on this site are moderated, you might need to wait until your comment is published. Spam and promotions will be deleted. Sorry for the inconvenience but we have moderated the comments for the safety of this website users. If you have any concern, or if you are not able to comment for some reason, email us at rahul@forcetrails.com