[solved] setCurrentItemIndex() doesn't seem to be working.

I created a form to edit existing database entries. The database is set to read/write. All the input fields are bound, everything works as far as editing an entry.

To select which entry to edit, I have a table that displays the data base. The table captures a click event on a row and stores the row number in a wix data session. This takes into account the number of items per page and which page is being displayed.

When the edit button is clicked a light box opens with the form for editing. I am able to edit the information and submit it.

Where i’m having difficulty is which entry is being edited. No matter what I do it always ends up at item index 0.

Regardless of whether I do setCurrentItemIndex() on page ready or database ready I always get item index zero. I’ve tried throwing in a save and/or refresh with no luck.

What is needed to get setCurrentItemIndex() to select and particular index?

There is a solution at the end but I wanted to go through how I got there first.

setCurrentItemIndex() is a function that returns a promise. What this means is that the function runs asynchronously. When the function is triggered it will run and once completed it will return some time later. This is in contrast to C where a function has to finish before the next one begins.

Once I learned this I found that these asynchronous events can be chained together. By adding .then() a command can be executed after the initial function successfully finishes. It looks like this.

$w(‘#dataset1’).setCurrentItemIndex(session.getItem(“row”)).then(() => { console.log($w(‘#dataset1’).getCurrentItemIndex(), “inside”) })

If the function finishes successfully then the current index of the dataset is displayed using the console. This showed that the function did not complete successfully because the index did not display.

Then I found that an error can be caught with a .catch() by stringing it together with the function. It looks like this.

$w(‘#dataset1’).setCurrentItemIndex(session.getItem(“row”)).then(() => { console.log($w(‘#dataset1’).getCurrentItemIndex(), “inside”) }) . catch (error => { console.log(error, “–error”) });

This will display the error that occurred in the console. This showed that I had a parameter that should be a number. This took me bit to figure out. Eventually when I hard coded a number into setCurrentItemIndex it worked. This lead me to suspect that session.getItem was not returning a number but a string. By parsing the string into a number everything was fixed. It looks like this.

$w(‘#dataset1’).setCurrentItemIndex(parseInt(session.getItem(“row”), 10));

Hope this helps someone.

3 Likes