clearSelection in table not working without delay

I am trying to programatically clear selection of a table, then select certain rows based on a database query. Essentially....

  1. Clear Selection
  2. Loop through DB records and select table records.

My Code:

ui_StudioFilterTable.clearSelection();

// and select rows where use_in_filter is true.
query_studios_for_checklist_studio_filter.data.forEach((row) => {
if (row.use_in_filter) {
ui_StudioFilterTable.selectRow({ mode: "key", key: row.id });
}

This wont work. It appears sometimes, the clearSelection is happening after the selection loop. I have to do a wait to get it to work.

ui_StudioFilterTable.clearSelection();

await new Promise(resolve => setTimeout(resolve, 500));

// and select rows where use_in_filter is true.
query_studios_for_checklist_studio_filter.data.forEach((row) => {
if (row.use_in_filter) {
ui_StudioFilterTable.selectRow({ mode: "key", key: row.id });
}

Why is thie behavior like this? FYI, the table is not hidden, not in a form, not in a tab.

Hi there @Highway20Productions,

I believe the problem is that the clearSelection() function is asynchronous, and it doesn't return a promise, so JavaScript may not be waiting for it to complete before moving on to your for loop where you select specific rows.

However, before we address that, I noticed something else in your code. The way that you are selecting rows, I think, is not correct. If you use the selectRow method with {mode: "key", key: row.id}, I believe that will end up only selecting the final row in your array, as it will end up only selecting one row at a time, and re-writing that selection for each time you loop through your row ids.

Instead, you should not do this with a loop, but instead provide an array of row ids to the function, like this:

ui_StudioFilterTable.selectRow({ mode: "key", key: [array of row ids]});

This will allow for multiple rows to be selected all at once.

Once you have fixed that, I think that your code should work. If it does not, in order to resolve the asynchronous issue, you could split the queries into two queries, the first query being to clear the selection. Then, you could add a success event handler that will run as soon as the first query is finished and it will call your second query (the one that selects the rows). If you are unfamiliar with success event handlers, you can read about them here.

I hope this helps! :grinning: