DatasetError: Invalid index when .add()

I’m writing some code using a repeater with input elements from an example found on this site, it’s good, but there’s an error in the code which I have replicated in my code.

Below is the function that’s causing the data set error on the .add() method for the dataset. It works mostly, but there seems to be a pattern.

1 - add item
2- add item
3- add item
4-delete item in step 2
5-add item ** error **

Has anyone seen this issue and what the resolution?

export async function buttonAddExercise_click ( event ) {
$w ( ‘#textEmpty’ ). hide ();

**await**  $w ( '#datasetMain' ). add (); //getting error 

let  item  =  $w ( "#datasetMain" ). getCurrentItem (); 

$w ( '#buttonAddExercise' ). disable (); 

$w ( "#repeater" ). forEachItem (( $item ,  itemData ,  index ) => { 
    $item ( "#boxExercise" ). style.backgroundColor  = ( index  %  2  ===  0 ) ?  "#FAF0E6"  :  "#FFEFD5" ; 
    $item ( "#textExerciseOrder" ). text  =  String . fromCharCode (( index ) +  'A' . charCodeAt ( 0 )) 
    
    if  ( item._id  ===  itemData._id ) { 
        $item ( "#buttonEdit" ). disable (); 

        $item ( '#dropdownExercises' ). show (); 
        $item ( '#inputExercisedetail' ). show (); 
        $item ( "#textExercisedetail" ). hide (); 
        $item ( "#textExercisename" ). hide (); 
    } 
}); 

}

Check this out for one such occurence.

External Media