title: Appending rows in a Loop - Google Spreadsheet
body: <p>I have an app script which uses the YouTube API to get videos from YouTube for a channel. YouTube only returns 50 results at a time. </p>
  
  <p>How do I append rows in the spreadsheet each time I get the next set of results</p>
  
  <p>The essence of my question is, how does one update rows on the spreadsheet in a For Loop. </p>
  
  <p>I tried. <code>sheet.appendRows(object [])</code> and that does not work. </p>
  
  <p>Any ideas ?</p>
  
  <p>My Script</p>
  
  <pre><code>function searchbySafety(safety) {
  
    var first_response = YouTube.Search.list('id,snippet',{
          channelId: 'UCpZG4Vl2tqg5cIfGMocI2Ag' ,
          maxResults: 50,
          safeSearch: safety
    });
  
    Create_headers();
    for (var i = 0; i &lt; first_response.items.length; i++) {
        var item = first_response.items[i];
        Logger.log('[%s] Title: %s', item.id.videoId, item.snippet.title);
        gen_results(first_response, safety);
        write_range(data);
    }
  
    var nextPageToken = first_response.nextPageToken;
    while(nextPageToken != null) {
        var videoresponse = YouTube.Search.list('id,snippet', {
          channelId: 'UCpZG4Vl2tqg5cIfGMocI2Ag' ,
          maxResults:50,
          pageToken: nextPageToken,
          safeSearch: safety
        });
  
  
        for (var i = 0; i &lt; videoresponse.items.length; i++) {
            var item = videoresponse.items[i];
            Logger.log('[%s] Title: %s', item.id.videoId, item.snippet.title);
            //gen_results(videoresponse, safety);
            //write_rest_data(data);
        }
        nextPageToken = videoresponse.nextPageToken;
    }
  
  }
  
  function gen_results(response, safety){ 
    for (var i = 0; i &lt; response.items.length; i ++)
    {
       var item = response.items[i];
  
       row = [item.snippet.title, "https://www.youtube.com/watch?v=" + item.id.videoId, safety];
       data[i] = row;
    }
    return data;
  }
  
  function write_range(data){
    var range = report_sheet.getRange(2,1,50,3);
    range.setValues(data);
  }
  
  function Create_headers(){
    var ss = SpreadsheetApp.getActiveSpreadsheet(); 
    var sheets = ss.getSheets();
    var sheet = sheets[3];
    Logger.log(sheet.getName());
    var headers = [
      ["Title","URL","Safety"]
    ];
    var range = sheet.getRange("A1:C1");
    range.setValues(headers);
    report_sheet = sheet;
  }
  </code></pre>