2

I am retrieving a set of values from apex through JS, I want to preselect the the first option in the Lightning-combobox (the retrieved values are different for different users). I used @track variable and tried to set the value onLoad using connectedcallback. Below is the code snippet

HTML

<lightning-layout-item padding="around-small">
        <lightning-combobox
       name="objPicklist"
       label="Objects"
       value={selectedObj}
       options={objects}
       onchange={displayObjRecords} >
    </lightning-combobox>

JS file

@track selectedObj;
objects = [];

connectedCallback(event) {

optionList({
    userID : this.currentUser,
})
.then(result=>{
    var i;
    
    for(i = 0; i < result.length; i++){
        const option = {
            label : result[i],
            value : result[i]
        };
        this.objects = [...this.objects, option];
        
    }
    //SETTING UP THE VALUE HERE.
    this.selectedObj = this.objects[0].value;
    
})
.catch(error => {
    this.error = error;
    console.log('Error : '+ JSON.stringify(this.error));
})

}

I would like to default the first option retrieved in the lightning combobox. How can I do it in LWC?

3
  • What is the error? You code looks fine. Dec 22, 2020 at 14:36
  • @NagendraSingh there is no error, but the value is not populating. Dec 22, 2020 at 14:37
  • I just tried it and it works well. Your result might be null or blank or something. Dec 22, 2020 at 14:40

1 Answer 1

1

I tried this and it works well. Instead of cloning the object, just take a local variable and push the records in that, and finally assign it like this this.objects = testPush;

    let testPush = [];
    for(let i = 0; i < 10; i++){
        const option = {
            label : 'result'+[i],
            value : 'result'+[i]
        };
        testPush.push(option);

    }
    this.objects = testPush;
    this.selectedObj = this.objects[0].value;

UPDATE

Even cloning works :

    for(let i = 0; i < 10; i++){
        const option = {
            label : 'result'+[i],
            value : 'result'+[i]
        };
        this.objects = [...this.objects, option];

    }
    this.selectedObj = this.objects[0].value;

Debug client side if the code is not working. Value might be null or something. But this works fine.

3
  • Were you able to display the default in the combobox? I can see the values from client side. Am able to print it Dec 23, 2020 at 6:56
  • Yes. I was able to do that. Dec 23, 2020 at 6:57
  • I do not know what's the reason. I can not figure out why it's not displaying the value Dec 23, 2020 at 9:00

You must log in to answer this question.

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