0

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
  • Are you getting some error? Commented Dec 22, 2020 at 14:27
  • @AbrahamLabkovsky Nope, The value is just not populating. Commented Dec 22, 2020 at 14:29
  • @PragadeeshDharshaV your implementation is correct and it should work, if it's not working then what I can assume is optionList() is not returning anything, try debugging it. Also, do add a null and length check before accessing the first element of the response array Commented Dec 24, 2020 at 7:59

1 Answer 1

1

Here's my version,

It seems to be working fine here:

https://webcomponents.dev/edit/enWpiQZZx8jl1OlicDeH

I made the object property reactive:

  @track objects = [];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.