0

I am just trying to add simple toast component on community page based on picklist value of type field. But I am getting callback error. I am not able to resolve this error. Any help is much appreciated.

Lightning Component

    <aura:handler name="init" value="{!this}" action="{!c.init}" />
    <aura:attribute name="save" type="Boolean" default="false"/>
    <aura:attribute name="institution" type="Account" default = "{'sobjectType':'Account', 'Type__c':''}"/>  




    <aura:if isTrue="{!v.save}">        
        <div class="slds-notify slds-notify_alert slds-theme_alert-texture slds-theme_info" role="alert">
            <span class="slds-assistive-text">info</span>
            <span class="slds-icon_container slds-icon-utility-user slds-m-right_x-small" title="Description of icon when needed">
                <c:svg class="slds-icon slds-icon_x-small" xlinkHref="{!$Resource.SLDS231 + '/assets/icons/utility-sprite/svg/symbols.svg#user'}" />
            </span>
            <h2>Message</h2>
        </div>
    </aura:if>

</aura:component>

JS COntroller

({
    init : function (component, event, helper) {
        var a = component.get('c.loadAccountInfo');
        $A.enqueueAction(a);
    },
    loadAccountInfo: function(component, event, helper) {
        var inputRecordId = $A.get("$SObjectType.CurrentUser.Id");
        var action = component.get("c.GetUserAccount");
        action.setParams({ userId : inputRecordId });

        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var objResults = response.getReturnValue();
                component.set("v.institution", objResults);
                if(objResults.Type__c != null && objResults.Type__c === "Approved"){
                    component.set("v.save", 'True');

                }
            }
            else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        console.log("Error message: " + 
                                    errors[0].message);
                    }
                } else {
                    console.log("Unknown error");
                }
            }
        });

        $A.enqueueAction(action);
    },
})

controller

public without sharing class customLookUpController {


    @AuraEnabled
    public static Account GetUserAccount(string userId)
    {
        list<User> lstUser;
        User currentUser;
        boolean blnResult = false;
        Account curAccount = null;
        try
        {

            lstUser  = [SELECT Id, ContactId, AccountId FROM User WHERE Id = :userId]; 

            if(lstUser != null && lstUser.size() >0 )
            {
                currentUser = lstUser.get(0); 
                if(currentUser.AccountId != null)
                {
                    list<Account> lstAccount = [SELECT Id,Name,Type__c
                                                FROM Account
                                                WHERE   Id = :currentUser.AccountId]; 

                    if(lstAccount != null && lstAccount.size() >0 )
                    {
                        curAccount = lstAccount.get(0);
                    }
                }

            }
        }
        catch(DmlException e) {
            System.debug('The following exception has occurred' + e.getMessage());
        }

        return curAccount;
    }


}

Error

Error in $A.getCallback() [Cannot read property 'Type__c' of null]

1 Answer 1

1
  1. You should implement proper error handling in apex using AuraHandledException.
  2. Apex code should always be bulkified - you should return list or map. And process it in javascript accordingly - you can use 1st record if needed.
  3. Javascript is case-sensitive. Its true. (not True or 'True')
  4. No problem if you want to implement fine-tuned exceptions like DMLException, but always catch generic exceptions in the end.

Lightning JS:

loadAccountInfo: function(component, event, helper) {
    var inputRecordId = $A.get("$SObjectType.CurrentUser.Id");
    var action = component.get("c.GetUserAccount");
    action.setParams({ userId : inputRecordId });

    action.setCallback(this, function(response) {
        var state = response.getState();
        if (state === "SUCCESS") {
            var objResults = response.getReturnValue();
            if(objResults) {
                let institution = objResults[0]; // if objResults is not null, we are getting list of accounts
                component.set("v.institution", institution);
                if(institution.Type__c != null && institution.Type__c === "Approved"){
                    component.set("v.save", true); // javascript boolean is true, not True
                }
            } else {
                console.error('Account not found'); // implement and show toast
            }
        }
        else if (state === "ERROR") { // show toast
            var errors = response.getError();
            if (errors) {
                if (errors[0] && errors[0].message) {
                    console.log("Error message: " + 
                                errors[0].message);
                }
            } else {
                console.log("Unknown error");
            }
        }
    });

    $A.enqueueAction(action);
}

Apex:

public static Account GetUserAccount(string userId)
{
    try {
        list<User> lstUser = [SELECT Id, ContactId, AccountId FROM User WHERE Id = :userId];
        if(lstUser != null && lstUser.size() >0 && lstUser.get(0).AccountId!=null) {
            return [SELECT Id,Name,Type__c
                    FROM Account
                    WHERE Id = :lstUser.get(0).AccountId];
        } else {
            return null;
        }
    }
    catch(Exception e) {
        throw new AuraHandledException(e.getMessage());
    }
}
3
  • I have refactored my code as you recommended. Thanks for all those suggestions. Unfortunately that didn't resolve my issue or made error message more meaningful. I am still getting the same error when adding component to the community.
    – Ricky
    Jul 27, 2019 at 4:33
  • Can you show updated code in apex and js Jul 27, 2019 at 4:48
  • 1
    My bad I didn't make changes to the js controller where you used let block scope constant. Thank you so much for your help. This has resolved my issue.
    – Ricky
    Jul 27, 2019 at 13:06

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .