Alan Humphrey
Alan Humphrey

Reputation: 553

async when leaving a page

I have a onClick handler on an element. The handler validates data and saves it to a local data store via an async function. Simplified code:

main () async {
  Future validateAndSaveData(Event e) async {
    Map inputData = {};
    var inputs = querySelectorAll("input, select");
    for (var input in inputs){
      inputData[input.id] = input.value;
    }
    var error = currentPage.validate(inputData);
    //e.preventDefault();
    if (error.isEmpty){
      try {
        await currentPage.saveSurvey(inputData);
      } catch (e){
        print (e);
      }
    } else {
      currentPage.handleErrors(error);
      e.preventDefault();
    }
    print ("after validation/save");
  }

  querySelector("#next")
    ..onClick.listen(validateAndSaveData);
}

If the code is executed as is the print ("after validation/save") is never executed and the data is not saved. If I uncomment the e.preventDefault() the data is saved and the print is executed.

It appears that the page is left before the await completes.

How can I ensure that the await currentPage.saveSurvey(inputData) line completes?

Running Dart 1.18.1 under Dartium on Ubuntu.

Upvotes: 1

Views: 163

Answers (1)

Alan Humphrey
Alan Humphrey

Reputation: 553

For anyone else having this problem I ended up changing the element to

<button id="next" data-next-page="station/1" class="btn btn-primary pull-right">Next</button>

and adding this line to the end of the validateAndSaveData routine.

window.location.assign((e.target as ButtonElement).dataset["next-page"]);

Upvotes: 0

Related Questions