0

Edit: Figured it out, details in the answers.

Original Question

I have a wire in my JavaScript code to get the results of a SOQL query. It is an aggregate query to get the maximum of a certain field.

My goal is to return the maximum when results exist, otherwise return an empty string.

It works as intended when results exist. However, when no results exist, instead of functioning as intended, it returns an error instead of an empty string.

Error:

Error: newValue cannot be undefined. 
Observable name: MapWithFilterOnSubscribeBehaviorSubject <= DistinctUntilChanged <= RootObservable: lds.Apex::controller:wiredMethod:false:{}, newValue: undefined
    at Ca.emitValue (lds.js:2)
    at eval (lds.js:2)
    at Ta.eval [as next] (lds.js:2)
    at fa.next (lds.js:2)
    at va._nextWithErrorHandling (lds.js:2)
    at eval (lds.js:2)
    at Set.forEach (<anonymous>)
    at va.emitValue (lds.js:2)
    at eval (lds.js:2)
    at Ta.eval [as next] (lds.js:2)

JavaScript:

@wire(wiredMethod)
wiredResult(result) {
    this.result = result;

    // get the data or the error returned by the wire
    const { error, data } = result;
    if (data) {
        this.data = data;
        this.error = undefined;
    } else if (error) {
        console.log(error)
        this.error = error;
        this.data = undefined;
    }
}

Apex:

@AuraEnabled(cacheable=true)
public static String wiredMethod() {
    AggregateResult[] results = [SELECT MAX(Name) max FROM Object__c WHERE Available__c = true];
    if (results.size() == 0) return '';
    else return (String) results[0].get('max');
}

Again, this works fine when the above query returns results. But when there are no results, I get an error instead of the empty string ''.

I have already checked similar questions (here, here) on StackExchange and they have not provided an answer to my question, since I think I have properly used a list to store the results of the query (if I haven't, let me know) and I have also checked to see if the length of the list is zero.

Why am I getting the above error instead of returning an empty string, and how do I fix this?

1 Answer 1

1

I have done some more debugging and figured it out. For anyone who stumbles upon this in the future with the same problem - the aggregate query will still return a result, so the list will have size 1, but the result will have value null. So the proper handling of this is:

@AuraEnabled(cacheable=true)
public static String wiredMethod() {
    AggregateResult[] results = [SELECT MAX(Name) max FROM Object__c WHERE Available__c = true];
    if (String.valueOf(results[0].get('max')) == null) return '';
    else return (String) results[0].get('max');
}

You must log in to answer this question.

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