[SalesForce] get the value from force:RecordData on Init handler

Is there a way we can get the value from force:RecordData on init ? I am getting the onclick event of a button.

<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <aura:attribute name="recordId" type="String"/> 
    <aura:attribute name="showButton" type="Boolean" default="false"/>
    <aura:attribute name="Opportunity" type="Object"/>   
    <aura:attribute name="parentOpp" type="Object"/>
    <aura:attribute name="oppLoadError" type="String"/>
    <force:recordData aura:id="oppRecordLoader"
                      recordId="{!v.recordId}"
                      fields="Id,
                              Name,
                              AccountId,
                              Cohort_Sem__r.End_date__c,
                              LeadSource,
                              Staff_Referral_Detail__c,
                              lead_source_detail__c"
                      targetRecord="{!v.Opportunity}"
                      targetFields="{!v.parentOpp}"
                      targetError="{!v.oppLoadError}"
                      />

JS:

doInit: function(component, event, helper) {           
         var opp = component.get("v.parentOpp");         
         console.log('Name Value: '+ opp.Name);
    }

Error:

Action failed: c:createIWSRecord$controller$doInit [Cannot read
property 'Name' of null] quickActionHandlerHelper.js failed to create
component – forceChatter:lightningComponent

Best Answer

force:recordData handles loading the record(s) asynchronously. As such, it will not be available during the init handler (there hasn't been a chance to run asynchronous code yet), and will likely not be available in the first render/afterRender cycle either.

The official method is to use the recordUpdated event.

<aura:attribute name="record" type="Asset" />

<force:recordData layoutType="FULL"
                  recordId="{!v.recordId}"
                  targetFields="{!v.record}"
                  recordUpdated="{!c.recordUpdate}" />

({
    recordUpdate: function(component, event, helper) {
        alert(component.get("v.record").Name);
    }
})
Related Topic