Sometimes there is a need to update the data of a child component in Salesforce that is not directly linked to the component but both the components share the same parent. So to refresh the data of the other child component linked to the same parent component you will have to create an API method in the child component you want to target and call that function from the parent component you hit from the other child component.
Let’s have a look at an example of the current requirement. Suppose you have a parent component that displays 2 lists but at a time it displays only one of them that is according to the value in the select box. It also has a ‘New’ button which opens a form in a modal on the basis of the value selected in the same select box mentioned above. So now the form in the modal is under one child component and the list to be displayed is under another child component and the requirement is to refresh the list on the creation of a new record. So for this, you will have to create a custom event in the ‘New’ form modal component which will hit the parent component as shown below.
Child Component 1 - New Record LWC
const selectedEvent = new CustomEvent("lookupselected");
// Dispatches the event.
this.dispatchEvent(selectedEvent);
Parent Component - Parent Listing LWC
<c-create-new-record onlookupselected={handleNewRecordSelection}></c-create-new-record>
This is the syntax for calling the new Record child component.
handleNewRecordSelection() {
this.template
.querySelectorAll("c-record-listing")
.forEach((element) => {
element.refreshListingData();
});
}
This function is fired when the custom event dispatches from the child component.
Once the new record is created successfully it will hit the ‘onlookupselected’ function of the parent component and then the ‘handleNewRecordSelection’ will get fired and the code under it will get executed. As you can see, I have hit a function of the other child component so a call will be sent to it and the code under it will get fired.
Child Component 2 - Record Listing
@track recordData;
@api refreshListingData(){
return refreshApex(this.recordData);
}
What it will do is fire the refreshApex function to update the data in the ‘recordData’ variable and display it in the listing.
The only thing to keep in mind is the function should have @api annotation for the parent component to access it.
StudySection gives an opportunity to beginners and experts in .NET framework to go through StudySection’s .NET Certification Exam and get a .NET certification for enhancement of career in programming. If you have knowledge of the .NET framework then you can get a certificate through an online exam at StudySection.