0

I am trying to access parent component value in child component connectedcallback but showing as undefined..however, I am able to acess it in html but not in js.

Ex:

Child comp js:

@api res;    
connectedCallback()
        {
            getRecords()
            .then(data => {
                this.res = data;
                console.log('res'+JSON.stringify(this.res));
                console.log('data'+JSON.stringify(data));
                
            }).
            catch(error => {
                this.error = error;
                console.log('error'+JSON.stringify(error));
            })
        } 

parent js:

@api orgdatafromp;
connectedcallback(){
console.log('orgdatafromp'+this.orgdatafromp);
}

orgdatafromp value is undefined.

what wrong i am doing here?

note :it bring the value in rendercallback

1
  • pass the data attribute in child component by calling a child component in Parent html . please share html code for better help Sep 11 '20 at 9:43
0

Refer this it may be helpful:

https://salesforcediaries.com/2019/07/24/lwc-communication-part-1-passing-data-from-parent-to-child-component/

and if you want ot pass from connectedCallback then you should refer the same name and it should be used as attribute and pass the value to Child component. you can share html as well for better answer.

0

When you call apex, it is called &asynchronously*. This means that the child connectedCallback happens before the Apex call completes. You can see the same problem if you write this:

@track res;
connectedCallback() {
    getRecords()
    .then(data => {
        this.res = data;
        console.log('res'+JSON.stringify(this.res));
        console.log('data'+JSON.stringify(data));
        
    }).
    catch(error => {
        this.error = error;
        console.log('error'+JSON.stringify(error));
    })
    console.log(this.res); // --> undefined
} 

Note that res should not be marked as @api, because that means it is supposed to be read-only at the parent level.

Regardless, you can't access the data in the child on connectedCallback, as the Apex hasn't had a chance to run yet. Use a setter instead:

_orgdatafromp;
@api set orgdatafromp(value) {
  // Do something with the incoming value
}
get orgdatafromp(value) {
  return this._orgdatafromp;
}
2
  • Could you please provide an example who can we access get/set values between parent to child.
    – Bibbi
    Sep 11 '20 at 10:54
  • @Sravanthi The get/set methods are called when data moves between parent and child. The problem is that you need to wait until the Apex method returns a value.
    – sfdcfox
    Sep 11 '20 at 11:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.