[SalesForce] Lightning Components Basics – Connect to Salesforce with Server-Side Controllers- Queries

As part of these module, can you help me understanding the below logic

in order to display the expense from APEX, below is the logic used

({
    doinit : function(component, event, helper) {
        var action = component.get("c.getExpenses");
        action.setCallback(this, function (response) {
            var state = response.getState();
            if (component.isValid() && state == "SUCCESS") {
                // var expview = component.get("v.expenses");
                // var parseRes = JSON.parse(JSON.stringify(response.getReturnValue()));
                // expview.push(parseRes); // component.set("v.expenses",expview);
                component.set("v.expenses", response.getReturnValue());
            } else {
                console.log(state);
            }
        });
        $A.enqueueAction(action);
    }
})

Apex:code
public class ExpensesController {

@AuraEnabled
public static List<Expense__c> getExpenses(){
    return [Select Id,Amount__c,Client__c,Date__c,Reimbursed__c,Name from Expense__c] ;       
} 

Aura Attribute expenses is getting set with the controller response (component.set("v.expenses",response.getReturnValue());). But If I want to use the commented lines, by doing a push and then set the component. It didn't work. WHy is that so ? I am doing a component get and then pushing the value which is the way even showed in the later section of this module while saving an expense record.

When to use the PUSH and when i can directly do a component.set?

can anyone help me in clarifying the doubts ??

Best Answer

When you Push you are pushing a single value.

Your getExpenses returns a list so you would need to iterate over the results and push each iteration onto expenses.

In the trailhead module, the push is used as part of saveExpense which returns a single expense which is why pushing the returnValue works.

So when returning a list simply use component.set if you want to replace all values of expenses or if you want to add to iterate over the results pushing each one

I have not tried it but in principle when returning a list from the controller you should be able to add all values to the attribute using concat as such which would be additive to the existing values.

var expview = component.get("v.expenses");
var parseRes = response.getReturnValue(); //Assuming this is a list
expview.concat(parseRes);

Related Topic