[SalesForce] Preselecting Rows on Datatable Doesn’t Work in LWC (max-row-selection=1)

For some reason, programmatically selecting a single row doesn't work in my datatable. To give a little background, I'm trying to preselect the very first row in my datatable by default. I use wire to retrieve the records to display. All of that is good except when I declare the datatable as max-row-selection=1, the row isn't being preselected at all. With max-row-selection of 2 or more, the rows are being preselected just fine.

HTML-Markup

<div class="slds-table">
<template if:true={contacts}>
    <lightning-datatable 
        data-id="contactTable"
        data={contacts} 
        columns={columns} 
        key-field="id" 
        selected-rows={preselectedContactRow}
        **max-row-selection=1**>
    </lightning-datatable>
</template>
</div>

JS

@track preselectedContactRow = [];
@track contacts;

// inside the wire service

this.preselectedContactRow = this.contacts.map(record=>record.id)

// ...

console.log('Rows : ', JSON.stringify(this.preselectedContactRow)); 
// record ids are being passed to this tracked variable successfully, and may contain single or multiple record ids

According to this documentation, my current setup above should still work..

If max-row-selection is set to a value less than the number of selected rows, only the specified number of rows will be selected. For example, if you set max-row-selection to 2 and pass in ['a', 'b', 'c'] to selected-rows, only rows a and b will be selected.

I've already tried the following:

// a. JS timing events didn't work

setTimeout(() => this.preselectedContactRow = this.contacts.map(record=>record.id));

// b. Passing a list to @track variable didn't work

let c_ids = [];
if(this.contacts){
   for (let i = 0; i < this.contacts.length; i++){
        c_ids.push(this.contacts.Id);
   }
   this.preselectedContactRow = c_ids;
}

// c. No, even with just one id still didn't work

this.preselectedContactRow = [...this.contacts].map((record, index) => {
   if(index == 0){
       return record.id;
   }
});

// d. Even passing a hardcoded id of a record that I know will appear in the datatable didn't work

this.preselectedContactRow = ['0011e00000xxxxxxxx'];

Problem: The @track variable for selected-rows will contain an id, but the row will never be preselected in the datatable.

Question: Given all that I've tried above, in regards to single row selection in lightning datatable, what's the correct or best way to preselect a record programmatically?

Thank you.

Best Answer

It was due to the fact that the selected-rows were assigned yet my datatable is yet to render. In my case, I was using modals and my datatable shows up in the second modal. When moving to the modal showing the datatable, I simply needed to call this.preselectedContactRow = this.contacts.map(record=>record.id)); in the on click next event again.