0

this is my first post on Stack, and I am new to creating web apps. I've done some searching and I think my issue has to do closures/forEach/let...
Found here - JavaScript closure inside loops – simple practical example But I am struggling on incorporating that into my app and need some help please.

I am using Firebase Realtime DB where I am pushing some data and pulling the uID of that push, then I use that same data to create a Google Calendar entry. I then retrieve that eventID from Calendar and then update the corresponding database node. So this works when I create a single entry at a time. What I then did, was I added the option to send multiple entries at once (this depends on a datetime-local input). So I have put these multiple datetimes into an array and they send correctly to Firebase and to Calendar, but where my bug is, is that only the last Calendar eventID is being updated in Firebase. It seems that the for loop over the array of date runs through before calendar can get the eventID and update Firebase. This was seen due to only my last date in the array having the associated calendar eventID. So yeah I think the issue is the global variable newPushId, but I am not sure at the moment how to fix it. All this is new and struggling to understand.

Sorry it's long, I would rather leave my code in there in case someone has any tips. If people would prefer me to shorten it, I will. Thank you in advance for the assistance.

Here's my main function that runs on submit.

    function sendInstantBook() {
// checkBookForm listed in services
  if (checkInstantBookForm()) {
    // Get variables from the form.
    var address = $('#instant-book-change-address').val();
    var instructor = $("#instant-book-instructor").children(":selected").attr("id");
    var transmission = $("#instant-book-transmission").children(":selected").attr("id");
    var duration = $("#instant-book-duration").children(":selected").attr("id");
    var start0 = $('#instant-book-start0').val();
    var multipleLessons;
    if (getLessonTimes() !== false) {
      multipleLessons = getLessonTimes();
    }
    multipleLessons = multipleLessons.split(',');
    // var recurring, interval, frequency, count;
    // if ($('#recurring-checkbox').is(":checked")) {
    //   recurring = true;
    //   interval = $('#instant-recurring-interval').val();
    //   frequency = $("#instant-recurring-freq").children(":selected").attr("id");
    //   count = $('#instant-recurring-count').val();
    // } else {
    //   recurring = false;
    //   interval = false;
    //   frequency = false;
    //   count = false;
    // }

    var sortAsc = new Date(start0).getTime();
    // var sortDes = 9999999999999 - sortAsc;
    var date0 = start0.split('T')[0];
    var timeStart0 = start0.split('T')[1];
    var timeFinish0 = addTimes(timeStart0, duration);
    var paymentType = $('input[name="instantPayment"]:checked').val();
    var paid = $('input[name="instantPaymentCheck"]:checked').val();
    var paymentNumber = getPaymentNumber(paymentType);
    var paymentDate = getPaymentDate(paid, date0);
    var email = adminStudentDetails.email;
    var phoneNumber = adminStudentDetails.phoneNumber;
    phoneNumber = phoneNumber.replace(/\s/g, "");
    var firstName = adminStudentDetails.firstName;
    var lastName = adminStudentDetails.lastName;
    var studentName = firstName + ' ' + lastName;
    var amount = getAmount(duration);
    var tracking = getTracking(duration);

    if (multipleLessons.length == 1) {
      // Create JSON object With the request's details and push to server
      var data = {
        "address" : address,
        "amount" : amount,
        "booked" : true,
        "calID" : false,
        "cancelled" : false,
        "date" : date0,
        "dateSortAsc" : sortAsc,
        // "dateSortDes" : sortDes,
        "duration" : duration,
        "email" : email,
        "firstName" : firstName,
        "instructor" : instructor,
        "lastName" : lastName,
        // "newStudent" : newStudent,
        "paymentDate" : paymentDate,
        "paymentType" : paymentType,
        "paymentNumber" : paymentNumber,
        "phoneNumber" : phoneNumber,
        "prepaid" : paid,
        // "recurring" : recurring,
        "studentName": studentName,
        "time": timeStart0 +  ' - ' + timeFinish0,
        "tracking": tracking,
        "transmission" : transmission,
        "type" : "Lesson",
      };
      // var recurringData = {
      //   "interval" : interval,
      //   "frequency" : frequency,
      //   "count" : count,
      // };
      // push data to firebase
      dbrefLessons.push(data).then((snap) => {
        newPushUid = snap.key;
// this is a global variable
      });
      insertCalEvent(data, updCalIdCallback);
      showSnackbar();
    }
    else if (multipleLessons.length > 1) {
      for (var i = 0; i < multipleLessons.length; i++) {
        eachDate = multipleLessons[i].split('T')[0];
        eachDateSortAsc = new Date(i).getTime();
        eachStart = multipleLessons[i].split('T')[1];
        eachFinish = addTimes(eachStart, duration);

        // Create JSON object With the request's details and push to server
        var dataMultiple = {
          "address" : address,
          "amount" : amount,
          "booked" : true,
          "calID" : false,
          "cancelled" : false,
          "date" : eachDate,
          "dateSortAsc" : eachDateSortAsc,
          // "dateSortDes" : sortDes,
          "duration" : duration,
          "email" : email,
          "firstName" : firstName,
          "instructor" : instructor,
          "lastName" : lastName,
          // "newStudent" : newStudent,
          "paymentDate" : paymentDate,
          "paymentType" : paymentType,
          "paymentNumber" : paymentNumber,
          "phoneNumber" : phoneNumber,
          "prepaid" : paid,
          "studentName": studentName,
          "time": eachStart +  ' - ' + eachFinish,
          "tracking": tracking,
          "transmission" : transmission,
          "type" : "Lesson",
        };
        // push data to firebase
        dbrefLessons.push(dataMultiple).then((snap) => {
          newPushUid = snap.key;
        });
        // push to calendar
        insertCalEvent(dataMultiple, updCalIdCallback);
      }
    }
    showSnackbar();
  }
}

And the calendar insert code.

    function insertCalEvent(linfo, updCalIdCallback) {
// function insertCalEvent(linfo, linfoRecur, updCalIdCallback) {

  // THIS WILL NEED TO CHANGE TO LOGGED IN USER RATHER THAN STUDENT DETAILS
  // or change it over to organizer
  var loggedInFirstName = studentDetails.firstName;
  var loggedInLastName = studentDetails.lastName;
  var today = new Date().toISOString();
  var todayDate = today.split('T')[0];
  var todayTime = today.split('T')[1].split('.')[0];

  // var interval = linfoRecur.interval;
  // var frequency = linfoRecur.frequency;
  // var count = linfoRecur.count;
  // if (interval == false) {
  //   interval = 0;
  //   frequency = 0;
  //   count = 0;
  // }

  var address = linfo.address;
  var amount = linfo.amount;
  var cancelled = linfo.cancelled;
  var date = linfo.date;
  var duration = linfo.duration;
  var email = linfo.email;
  var firstName = linfo.firstName;
  var lastName = linfo.lastName;
  var location;
  var newStudent;
  var instructor = linfo.instructor;
  var paymentType = linfo.paymentType;
  var paid = linfo.prepaid;
  var transmission = linfo.transmission;
  var type = linfo.type;
  var phoneNumber = linfo.phoneNumber;
  var time = linfo.time;
  var time1 = time.split(' - ')[0];
  var time2 = time.split(' - ')[1];

  if (linfo.location == undefined) {
  } else {
    location = linfo.location;
  }

  if (linfo.newStudent == true){
    newStudent = "NEW ";
  } else if (linfo.newStudent == undefined || linfo.newStudent == false) {
    newStudent = "";
  }

  if (paid == "Yes") {
    paid = "PD ";
  } else {
    paid = "Owes ";
  }

  if (paymentType == "Instructor") {
    paymentType = "Instructor ";
  } else if (paymentType == "Office") {
    paymentType = "Office ";
  } else if (paymentType == "Pack") {
    paymentType = "(input pack) ";
  }

  var event = {
    'summary': paid + paymentType + amount + ' - ' + newStudent + transmission + ' ' + type + ' - ' + firstName + ' ' + lastName + ' - ' + address + ' - ' + phoneNumber,
    'location': address,
    'description': 'Lesson generated by XLR8 app. \nInstructor - ' + instructor + '\nBooked by ' + loggedInFirstName + ' ' + loggedInLastName + ' at ' + todayDate + ' - ' + todayTime + '.\nStudent email - ' + email,
    'start': {
      'dateTime': date + 'T' + time1 + ':00+10:00',
      'timeZone': 'Australia/Brisbane'
    },
    'end': {
      'dateTime':  date + 'T' + time2 + ':00+10:00',
      'timeZone': 'Australia/Brisbane'
    },
  //   'attendees': [
  //   {'email': 'simon.curran.89@gmail.com'},
  // ],
    'reminders': {
      'useDefault': false,
      'overrides': [
        {'method': 'popup', 'minutes': 30}
      ]
    },
    // "recurrence": [
    //   "RRULE:FREQ="+ frequency + ";COUNT=" + count + ";INTERVAL=" + interval + ";"
    // ],
    // 'originalStartTime': date + 'T' + time1 + ':00+10:00',
    // 'recurringEventId': 'recurringEventId',
    // 'colourId': 10,
  };

  gapi.client.load('calendar', 'v3', function() {
    var request = gapi.client.calendar.events.insert({
      "calendarId": "primary",
      "resource": event
    }, function(err, event) {
        if (err) {
          console.log("There was an error contacting the Calendar service: " + err);
          return;
        } else {
          console.log("Event created: %s", event.htmlLink);
        }

      });

    request.execute(function(resp) {
      // console.log(resp);
      // var calID = resp.id;
      return updCalIdCallback(resp.id);

    });
  });
}

And the callback function:

    function updCalIdCallback(calID) {
  var updatedCalID = {
    "calID" : calID,
  };
  dbrefLessons.child(newPushUid).update(updatedCalID);
  console.log(calID);
  console.log(newPushUid);
  newPushUid = '';
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

0 Answers0