0

I'm really struggling to perform what I'm sure is a rather simple task. I'm using the Google Sheets API to extract data from a spreadsheet. I want to store the data in a Javascript object.

So far, I am able to successfully request the data from the API and I know that it is working because I can print it to the console. But I've been trying and failing to store this same data as an object.

I grabbed my code template from https://developers.google.com/api-client-library/javascript/start/start-js and https://developers.google.com/sheets/api/samples/reading.

This is my code currently:

<script src="https://apis.google.com/js/api.js"></script> 
<script> 
function start() {
    // 2. Initialize the JavaScript client library.
    gapi.client.init({
      'apiKey': 'key',
      // clientId and scope are optional if auth is not required.
      'clientId': 'client_id',
      'scope': 'profile'}).then(function() {
        // 3. Make the request
        return gapi.client.request({
          'path': 'https://sheets.googleapis.com/v4/spreadsheets/sheet_id/values/Sheet3'});
        }).then(function(response){
            console.log(response.result);
   }); 
};
// 1. Load the JavaScript client library. 
gapi.load('client', start);
</script>

It successfully prints to the log: enter image description here

But I have no clue how to store this data and access it later. I'd appreciate any help!

ZachTurn
  • 636
  • 1
  • 5
  • 14

1 Answers1

1

Use a callback function and a global variable. This is the only way since the function makes an asynchronous XHR request.

var results; // global variable. Only accessed after XHR returned response. 
function start() {
    // 2. Initialize the JavaScript client library.
    gapi.client.init({
      'apiKey': 'key',
      // clientId and scope are optional if auth is not required.
      'clientId': 'client_id',
      'scope': 'profile'}).then(function() {
        // 3. Make the request
        return gapi.client.request({
          'path': 'https://sheets.googleapis.com/v4/spreadsheets/sheet_id/values/Sheet3'});
        }).then(function(response){
            results = response; // update global variable, and then call your callback function
            onResultsSuccess(results); // response will also work.
   }); 
};
// 1. Load the JavaScript client library. 
gapi.load('client', start);

onResultsSuccess(data){
    console.log(data.result);
    // more code.
}

Further reading: How do I return the response from an asynchronous call?

Community
  • 1
  • 1
Adam Azad
  • 11,171
  • 5
  • 29
  • 70