Skip to content Skip to sidebar Skip to footer

Google Calendar Javascript Api - Add Multiple Events

I've been facing a problem when I'm trying to add multiple events to a Google Calendar via javascript v3 api. I have an array which entries are events like these: newEvent = {

Solution 1:

If you want to insert multiple events at once, you should use batch.

var batch = gapi.client.newBatch();
batch.add(gapi.client.calendar.events.insert({
    'calendarId': 'primary',
    'resource': events[0]
}));
batch.add(gapi.client.calendar.events.insert({
    'calendarId': 'primary',
    'resource': events[1]
}));
batch.add(gapi.client.calendar.events.insert({
    'calendarId': 'primary',
    'resource': events[2]
}));
            ......

batch.then(function(){
    console.log('all jobs done!!!')
});

Solution 2:

events[j] is being rebound on each iteration of the for loop. Try using an anonymous function to bind to the correct event:

var request;
for(var j = 0; j<events.length; j++) {

  console.log(events[j]);

  request = function(resource) {  // Function that returns a request.
    return gapi.client.calendar.events.insert({
      'calendarId': calendarId,
      'resource': resource
    });
  }(events[j]);  // Bind to the current event.
  request.execute(function(resp) {
    console.log(resp);
  });
}

See the following question for more details on JavaScript arrays and closures: JavaScript closure inside loops – simple practical example

Here is an easier-to-read version of the code above that moves all the processing into a function:

var makeRequest = function(resource) {
  console.log(resource);
  var request = gapi.client.calendar.events.insert({
    'calendarId': calendarId,
    'resource': resource
  });
  request.execute(function(resp) {
    console.log(resp);
  });
};

for(var j = 0; j<events.length; j++) {
  makeRequest(events[j]);
}

Solution 3:

As soredive, Mentioned, you need to use batch to add multiple events

why batch? The primary reason to use the batch API is to reduce network overhead and thus increase performance.

example:

createMultipleEvents() {
    const events = [ {
      'summary': 'sample test events1',
      'location': 'coimbatore',
      'start': {
          'date': '2018-08-29',
          'timeZone': 'America/Los_Angeles'
      },
      'end': {
          'date': '2018-08-29',
          'timeZone': 'America/Los_Angeles'
      }
  },
  {
    'summary': 'sample test events2',
    'location': 'coimbatore',
    'start': {
        'date': '2018-08-29',
        'timeZone': 'America/Los_Angeles'
    },
    'end': {
        'date': '2018-08-29',
        'timeZone': 'America/Los_Angeles'
    }
},
];
const batch = gapi.client.newBatch();
events.map((r, j) => {
  batch.add(gapi.client.calendar.events.insert({
    'calendarId': 'primary',
    'resource': events[j]
  }))
})
batch.then(function(){
  console.log('all jobs now dynamically done!!!')
});
  }

Post a Comment for "Google Calendar Javascript Api - Add Multiple Events"