[SalesForce] LWC best practice call child method

see example https://developer.salesforce.com/docs/component-library/tools/playground/q8rtcVIBf/79/edit

Parent component

<template>
    Value in Parent : {objMap.key}
    Value in Parent : {dummyStr}
    <lightning-button onclick={updateValue} label="Update Data"></lightning-button>
    <c-child obj-map={objMap} dummy-str={dummyStr}></c-child>
</template>

export default class App extends LightningElement {
    @track objMap = {key:"value"};
    @track dummyStr
    updateValue() {
        this.objMap.key = 'Value2';
        this.dummyStr = Math.random(); //  <---- ADD NEW VALUE
        this.template.querySelector('c-child').run();
    }
}

Child component

export default class Child extends LightningElement {
    @api objMap
    @api dummyStr

   @api
    run() {
        console.log(this.dummyStr); // <---- OLD VALUE????
    }
}

How to call child method from parent when need to use @api values?

Best Answer

This is expected behavior. The properties values will be passed down to child after the method javascript is finished running so that it collects all the changed properties and pushes the changed values down the chain. You can understand this by having the logs in change handler of dummyStr as shown here

enter image description here

You can implement it in 3 different ways:

Option 1: Use setTimeout (preferred)

As shown here, you can use setTimeout to invoke the child method AFTER the parent method completes processing. Using setTimeout will push the invocation into asynchronous thread because of which it will run later after synchronous thread.

setTimeout(()=>this.template.querySelector('c-child').run());

Option 2: Use Change handler

As shown here, you can use change handler in child api property which will be invoked after the property is changed.

@api 
get dummyStr() { 
    return this._dummyStr; 
}
set dummyStr(value) {
    this._dummyStr = value;
    console.log('dummyStr changed => ', this._dummyStr, value);
    this.run();
}

Option 3: Use method parameter

As shown here, pass the required changed properties as method parameters.

this.template.querySelector('c-child').run(this.dummyStr);
Related Topic