Error during LWC component connect phase: [Cannot read properties of undefined (reading ‘data’)]

In Salesforce, when creating and deploying an LWC component to a Lightning page, it might return an error: “Cannot read properties of undefined (reading ‘data’).” This error generally occurs when we try to deploy the component with undefined access or improperly initialized properties.

We might not get any errors in the code while creating and deploying the source code to the Salesforce org. It only happens while adding the LWC component on the Lightning page via the Lightning app builder.

In this Salesforce tutorial, we will view and analyse the code that returned the error “Cannot read the properties,” and then we will fix it.

Resolve LWC component connect phase error: Cannot read properties of undefined.

In my case, I got the error while I set a parent-child communication component setup where the child component emits a custom event, and the parent component listens to it. While adding a component on a Lightning app page, it returned the error “Cannot read properties of undefined (reading ‘indexOf’).”

Let’s see the code from the LWC components that were returning an error.

Child Component Javascript:

import { LightningElement } from 'lwc';

export default class ChildComponent extends LightningElement {
    productOptions = [
        { label: 'Laptop', value: 'Laptop' },
        { label: 'Smartphone', value: 'Smartphone' },
        { label: 'Tablet', value: 'Tablet' },
        { label: 'Smartwatch', value: 'Smartwatch' }
    ];

    handleProductChange(event) {
        const selectedProduct = event.detail.value;
        console.log('Selected Product:', selectedProduct); 
        });

Parent Component JavaScript:

The code below in the JS file of the Parent component was returning the error.

import { LightningElement, track } from 'lwc';
export default class ParentComponent extends LightningElement {
    @track selectedProducts; 

    handleProductSelect(event) {
        this.selectedProducts = event.detail.data.join(', '); 
    }
}

Returned error:

Salesforce LWC component error

Now, let’s analyse why it returned the connection phase error for the Parent JS file.

In the @track selectedProducts, no value is assigned to select products. After this, the “event.detail.data” is undefined, causing.join(‘, ‘) to fail and cause the error. So, we can see that the event is not structured correctly, and the component might try to render before the selected products are initialised.

Fixing the LWC component connect phase error:

1. First, we will fix the event handling in the child component with the correct code structure.

 handleProductChange(event) {
        const selectedProduct = event.detail.value;
        console.log('Selected Product:', selectedProduct); 

        const productEvent = new CustomEvent('productselected', {
            detail: selectedProduct,
            bubbles: true,
            composed: true
        });

        this.dispatchEvent(productEvent);
    }

In the event dispatching, we have introduced a custom event named ‘productselected’, allowing other components to listen to this event.

We have also implemented the Bubbling and Composition feature. When the execute “bubbles: true,” it allows the event to propagate up the DOM tree.

The composed: true ensures the event crosses the Shadow DOM boundary, making it accessible to parent components.

2. Now, we will fix the code of the parent component with the help of the code below.

import { LightningElement, track } from 'lwc';

export default class ParentComponent extends LightningElement {
    @track selectedProduct = 'None'; 

    renderedCallback() {
        const childComponent = this.template.querySelector('c-child-component');
        if (childComponent && !this.isListenerAdded) { 
            childComponent.addEventListener('productselected', this.handleProductSelection.bind(this));
            this.isListenerAdded = true; 
        }
    }

    disconnectedCallback() {
        const childComponent = this.template.querySelector('c-child-component');
        if (childComponent) {
            childComponent.removeEventListener('productselected', this.handleProductSelection.bind(this));
        }
    }

    handleProductSelection(event) {
        console.log('Product Selected in Parent:', event.detail); 
        this.selectedProduct = event.detail;
    }
}

In the above code of the parent JS file, we have assigned a default value as @track selectedProduct = ‘None,’ which was missing previously.

In the event handling, instead of using the event listener directly in the handler method (handleProductSelect(event)), we have used renderedCallback() to attach an event listener dynamically and remove it in disconnectedCallback() for proper event handling.

Unlike directly assigning event.detail.data.join(‘, ‘) in the previous method, assuming data exists in “event.detail.” We have used bind(this) when adding or removing event listeners for the correct context.

In the previous method, we didn’t define any event cleanup. In the code correction, we have used disconnectedCallback() to remove the event listener.

3. Now, save and deploy the changes to the Salesforce environment.

4. Navigate to the Lightning page and again deploy the LWC component to the page using the Lightning app builder.

Component Event handling error in Salesforce LWC

This way, we can fix and resolve the “LWC component connect phase error: Cannot read properties of undefined” error in Salesforce.

Conclusion

In this Salesforce LWC tutorial, we have learned to fix and resolve the “LWC component connect phase error: Cannot read properties of undefined” by analysing and modifying the existing code structure of the LWC component.

To avoid such errors, ensure the event data structure is correct and use optional chaining (?.) to access properties safely. Also, providing default values helps prevent null or undefined errors.

You may also like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.