Uncaught TypeError: Cannot read property 'apply' of undefined when calling function on parent LWC

616    Asked by Bhaanumatishukla in Salesforce , Asked on Jul 6, 2021

 I have a LWC I am embedding in a flow. The LWC embeds another LWC as a component. (its basically this one: https://live.playg.app/play/custom-carousel-with-lwc ) On the parent LWC my onclick event fires fine. But when I click on the embedded one it gives this error: Uncaught TypeError: Cannot read property 'apply' of undefined throws at Any ideas what I am doing wrong? Shouldn't a child LWC be able to invoke a parent function no problem?

my code


Answered by ananya Pawar

The typeerror: cannot read property 'apply' of undefined error was I was trying to call a function on the parent directly from the child and that doesn't work. You need to create a custom event on the child that the parent is listening for like this:

Parent HTML


Parent JS
handleSlideClicked(event) { console.log('in parent handle click' + event.detail); }
Child HTML
Child JS
@api slideIndex; handleSlideClick(event) { this.slideIndex = event.currentTarget.dataset.index; // Creates the event with the data. const selectedEvent = new CustomEvent("slideclicked", { detail: this.slideIndex, bubbles:true }); // Dispatches the event. this.dispatchEvent(selectedEvent); }


Your Answer

Answer (1)

Use Custom Events: Instead of directly calling the parent function, emit a custom event from the child LWC. The parent can listen for this event and then call the desired function. This is the Build Now GG recommended approach in LWC for communication between components.

1 Month

Interviews

Parent Categories