1

I have a combobox whose values are supposed to be dynamically added. For some reason this is not happening. I have found similar cases on this website but none of the solutions worked for me. Here is my code.

JS Code :


    @track items = []; //this will hold key, value pair
    connectedCallback(){
        getContactList()
                    .then(result => {
                          {
                            this.contacts = result;
                            for (var i = 0; i < this.contacts.length; i++) {
                                var contact = this.contacts[i];
                                console.log('contact:', contact);
                                this.items.push({ label: contact.channel, value: contact.channel });

                            }
                            console.log('this.items.length:', this.items.length);
                            console.log('this.items:', this.items);
                            console.log('deserialized items :', JSON.stringify(this.items));
                        }

                    })
                    .catch(error => {
                        this.error = error;
                    });
    }

HTML

           <div class="slds-col"> <lightning-combobox
                        name="elChannel"
                        label="Channel"
                        value={value}
                        placeholder="Select Channel"
                        options={items}
                        onchange={genericOnChange} >
                </lightning-combobox></div>

The console output shows that items is being filled properly, it is just not appearing in the combobox. The thing I don't understand is that contacts is displayed in a datatable and is updated properly when calling the function.

0

As far as i am concerned, the @track property rerenders when the value changes, in your case, data is an array, so if you sort it or add some elements using array.push() for example, the var value itself does not change as it is a reference.

Try using this statement after the for where you fill the items array:

this.items = JSON.parse(JSON.stringify(this.items));

This way you make an exact copy of that array, changing the reference of the var data, making the @track property rerender the combobox.

I hope this helps you

  • This is working great, thank you. – Sacha Dieryck Jan 15 at 10:57
1

The items variable's reference is indeed not altered. Consider pushing the items to a separate variable and assign it to your items variable later. Pseudo code:

let mappedItems = [];    
results.map(result => {
  mappedItems.push({label: result.label, value: result.value});
})
this.items = mappedItems;
  • This is also working, thanks. – Sacha Dieryck Jan 15 at 10:57

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.