Home > Software engineering >  How use sessionStorage with JS and Google Apps Script?
How use sessionStorage with JS and Google Apps Script?

Time:09-03

I am trying to avoid calling the server-side function getSuppliersForPoFromSS(orderPo, origin), if there is data available in the sessionStorage, but I am not sure I get the right structure:

**/
 * Gets determined supplier from Spreadsheet and builds a select input with options.
 * @param {Object} selecObject
 * @param {String} origin specifying where this is going to be obtained from
 */
function loadSuppliersForPoFromSS(selectObject, origin) {
  orderPo = selectObject.value;
  document.getElementById('selectSupplier').innerHTML = '';
   
  //My shot at it, trying to a 2D array. e.g.: [["Item1", "Item2"]]
  let ar = JSON.parse(sessionStorage.getItem(orderPo));
 
   
  if(!ar){   
  google.script.run.withSuccessHandler(function(ar) {
    let select = document.getElementById('selectSupplier');
    let options = select.getElementsByTagName('option');
    for (let i = options.length; i--;) {
      select.removeChild(options[i]);
    }
    let option = document.createElement("option");
    option.value = "";
    option.text = "";
    select.appendChild(option);
    ar.forEach(function(item, index) {
      let option = document.createElement("option");
      option.value = item.toLowerCase();
      option.text = item;
      select.appendChild(option)
    });
  }).getSuppliersForPoFromSS(orderPo, origin);
 } else {
  //Do I rewrit the part that builds the options with data from sessionStorage?
}

CodePudding user response:

Since google.script.run is asynchronous, which means the commands following it will not wait for google.script.run to complete and return you can create an internal function getAr() which will be called either as part of the success handler of google.script.run or by itself if sessionStorage returns a value.

function loadSuppliersForPoFromSS(selectObject, origin) {
  orderPo = selectObject.value;
  document.getElementById('selectSupplier').innerHTML = '';
  
  function getAr(ar) {
    let select = document.getElementById('selectSupplier');
    let options = select.getElementsByTagName('option');
    for (let i = options.length; i--;) {
      select.removeChild(options[i]);
    }
    let option = document.createElement("option");
    option.value = "";
    option.text = "";
    select.appendChild(option);
    ar.forEach(function(item, index) {
      let option = document.createElement("option");
      option.value = item.toLowerCase();
      option.text = item;
      select.appendChild(option)
    });
  }

  //My shot at it, trying to a 2D array. e.g.: [["Item1", "Item2"]]
  let ar = JSON.parse(sessionStorage.getItem(orderPo));
   
  if(!ar){   
    google.script.run.withSuccessHandler(function(ar) {
      getAr(ar);
    }).getSuppliersForPoFromSS(orderPo, origin);
  } 
  else {
    getAr(ar);
  }
}
  • Related