1

I'm trying to pass a list of string from Apex controller to Javascript but it does not seem to work

Code I tried:

Apex class

 @AuraEnabled
 public static List<String> getGroups(){
     string names;
     List<String> Groupnames = new List<String>();
     Http http = new Http();
     HttpRequest request = new HttpRequest();
     request.setMethod('GET');
     request.setHeader('X-ChatWorkToken',key);
     request.setEndpoint('https://api.chatwork.com/v2/rooms');
     HttpResponse res = http.send(request);
     LIST<Object> arr = (LIST<Object>) JSON.deserializeUntyped(res.getBody());
     for(integer i = 0; i < arr.size(); i++){
         Map<String, Object> firstMap = (Map<String, Object>)arr[i];
         names = (String)firstMap.get('name');
         Groupnames.add(names);
     }
     return Groupnames;
 }

Javascript

listofgroup:function(component, event, helper){
    var action = component.get("c.getGroups");
    console.log('received',response);
    action.setCallback(this, function(response){
        //var state = response.getState();
        // if(state === 'SUCCESS'){
            var res = response.getReturnValue();
            for(var i = 0; i < res.length; i++){
                //set the values here
                component.set("v.lstGroup",response.getReturnValue());
            }
        }
    // }
    )
}

dont know where I'm going wrong

1 Answer 1

3

Looks like you have forgotten to actually call (enqueue) the action.

Like this:

action.setCallback(this, function(response){
  //your other stuff
});
//add here:
$A.enqueueAction(action);

In your callback, to use as a select list, process something like this:

let groupValues = [];
let res = response.getReturnValue();
res.forEach( (value)=>{
  groupValues.push({label:value,value:value});
});
component.set("v.lstGroup",groupValues);
6
  • i completely missed that.. how can i check what is inside v.lstGroup
    – Tejas
    Apr 6, 2021 at 4:50
  • might be easiest to console.log it... console.log(JSON.stringify(component.get("v.lstGroup"))). Because it's a list of strings, you can also iterate it easily. Are you using it as a source for a picklist? Glad to help!! Apr 6, 2021 at 4:53
  • Thank you @Casper Harmer
    – Tejas
    Apr 6, 2021 at 4:54
  • 1
    Added a wee bit extra to show how to add the combobox items Apr 6, 2021 at 7:05
  • 1
    Thankyou @Caspar Harmer you made my day..
    – Tejas
    Apr 6, 2021 at 7:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.