2

So I have parent component and child components as so

<parent>
 <childl1 contracts = {contracts} oncontractsupdate = "handleContractsUpdate">
  <childl2 contracts = {contracts}>
   <childl3 contracts = {contracts}/>
  </childl2>
</childl1>
</parent>

parent.js :

contracts;
onInit(){
  someApi.getContracts().then(contracts => this.contracts = contracts);
}

handleContractsUpdate(event) {
  someApi.updateContracts(event.detail.data).then(contracts => this.contracts = contracts);
}

This is how I communicate from the childl3 to parent:

childl3.js

@api
contracts
handleUpdate() {
    this.dispatchEvent(new CustomEvent('contractsupdate', {
            bubbles: true,
            composed: true,
            detail: {
                data: someData
            }})
        );
    }
    

Now here it says I shouldn't be bubbling events and if I do I need to have a handler in every intermediate child and ensure the event is globally unique. https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.events_best_practices

If I don't use bubbles and composed true, would each intermediate listen and throw the event individually? This though seems very repetitive .

Also looked into https://www.lwc-redux.com/

Having redux would be a major refactoring but not sure how much of lwc-redux is supported at this point of time.

I am guessing a lot of people have the same issue(or maybe we just designed the UI not per lwc recommedation). Want to know how they deal with something like this..

1 Answer 1

1

This is a different approach from bubbling from child to parent, but would also work and hopefully simplify the implementation.

You could try using either LMS / pub-sub to isolate your messages from child to parent.

See LMS documentation here: https://developer.salesforce.com/docs/component-library/bundle/lightning-message-service/documentation

You could use APPLICATION_SCOPE to only handle events in the parent LWC that you actually want to handle.

Similarly you could use pubsub (you can find a sample implementation here)

then do something similar to this:

Child 3 LWC: fireEvent(this.pageRef, 'child3ToParent', payload)

Parent LWC:

connectedCallback() {
  registerListener('child3ToParent', this.handleChild3, this);
  // do other stuff...
}

disconnectedCallback () {
    unregisterAllListeners(this)
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .