Search code examples
google-app-maker

How to fix Maximum call stack size exceeded error in appmaker


Error I got

I'm currently validating a date box widget to prevent filing after a 30 days grace period. The date validation was working but after the alert prompted it wasn't going down(I was stock in here even after a couple of clicks). Also the date box is not going null.

function checkDateValidate(widget) {
  var form = app.pages.Newitem.descendants;
  var otdate = form.otDateBox.value; 
  var date = new Date();
  var pastdate = date.setDate(date.getDate() - 31);

  if(otdate <= pastdate) {
    alert('Date exceeds within 30 days grace period is invalid.');
    form.otDateBox.value = null;
  }
}

I expected to clear the date box widget.


Solution

  • This error sometimes happens because there is an infinite loop going on and this is your case. It is very important that you understand the difference between the onValueChange event handler and the onValueEdit event handler.

    The onValueChange:

    This script will run on the client whenever the value property of this widget changes. The widget can be referenced using parameter widget and the new value of the widget is stored in newValue.

    The onValueEdit:

    This script will run on the client whenever the value of this widget is edited by the user. The widget can be referenced using parameter widget and the new value of the widget is stored in newValue. Unlike onValueChange(), this runs only when a user changes the value of the widget; it won't run in response to bindings or when the value is set programmatically.


    Why is this happening?

    Since your logic is set on the onValueChange event handler, this will be triggered everytime the dateBox widget value is changed, even programmatically; Hence, form.otDateBox.value = null; is triggering the logic over and over again. The reason why it is being triggered over and over again is due to your comparison logic:

    if(otdate <= pastdate)
    

    Here, the value of otdate has become null wich when converted to number Number(null) the value is 0(zero). The value of pastdate is obviously a number greater than zero, eg 1555413900712. So obviously, zero is less than or equal to 1555413900712 and that is why you are triggering an infinite loop.

    So, in summary, there is only one way to fix this. Set the logic inside the onValueEdit event handler instead of the onValueChange.