[SalesForce] Change field value in lightning component

I'm trying to change the value of the field Instagram_followers__c of my Influencer__c object in my lighthning component. It's a really simple component: a refresh button wich check the number of followers when we click on it. But I don't know how to change the value of the Instagram_followers__c field.

My componenet :

<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId" access="global">
<aura:attribute name="recordId" type="Id" />
<aura:attribute name="Influencer" type="Influencer__c" />
<aura:attribute name="message" type="String"/>
<force:recordData aura:id="Influencer__c"
              recordId="{!v.recordId}"
              targetFields="{!v.Influencer}"
              layoutType="FULL"
              />
<p>Followers count for <b>{!v.Influencer.Instagram_account__c}</b> : <lightning:badge label="{!v.Influencer.Instagram_followers__c}"/></p>
<p>{!v.message}</p>
<lightning:button label="Refresh" iconName="action:refresh" title="Refresh followers count" onclick="{! c.refreshInsta }"/>

My controller:

({ 
refreshInsta : function(component, event, helper) {

    component.set("v.message", "Loading...");

    var instaUserName = component.get("v.Influencer.Instagram_account__c");

    var url = "https://mysite.com/GetFollowersCount.php?user=" + instaUserName;

    var request = new XMLHttpRequest();
    request.open('GET', url, true);

    request.onload = function () {
        var followers = this.response
        if(followers == 0){
            component.set("v.message", "An error occured. Please try again later (in 5min)");
        }else{
            component.set("v.message", "New followers count: " + followers);
            component.set("v.Influencer.Instagram_account__c", parseInt(followers))
        }

    }
    request.send();


}
})

But it doesn't work, I see the button on the page, I click, I wait, the followers count appear on the page (on the v.message field) but the record isn't changed.

Best Answer

At present, it appears to me that you code only makes a request. This is an asynchronous method that should have a callback of sorts when data is returned. You also need to have code that handles the asynchronous return from that call and then processes the data.

Once the data is returned, it then will need to process the results and set the new value for your Instagram_followers__c. This would typically be done using a helper method.

Related Topic