Sometimes you will want to store data on the client-side (i.e., in the user's browser session). For example, you might read data from a spreadsheet, transform it based on some user input, and then store it. This way, you don't have to re-read and re-transform each time you need it.
In `Code.gs`, write a function to load data as an array.
```JavaScript title="Code.gs"
function getData(){
// use your favorite method to load a range as an array
}
```
In `JavaScript.html`, create a variable to store the data to, a function to use the data, and a function to store the data wrapped in a Success Handler and triggered after some event (e.g., the DOM content has loaded).
```JavaScript title="JavaScript.html"
var data;
// This function displays or otherwise uses the data
function useData(data){
if(data){
// do something with the data
}
}
// This function reads the data and saves to data variable
function setData(){
google.script.run.withSuccessHandler(function(dataReturned){
data = dataReturned.slice();
useData();
}).getData()
}
// Call setData once DOM content is loaded
document.addEventListener('DOMContentLoaded', function(){
setData();
}
```
You can also put the function within a callback of another function (e.g., on page load).
You need to use slice because otherwise data will be set as a reference to the ephemeral `dataReturned` object and become undefined. Slice with no parameters returns a deep copy of an array.
You also need to handle the time it takes to return the data from the server side. The script will simply keep chugging after it runs `getData`. If you access the `data` object before the data are returned, you'll be working with an empty object. Because the `setData` function is called with a Success Handler after `getData` runs successfully, it will only execute after the data successfully return from the server. You can call a `useData` function or include some other logic within the `setData` function.
If you will be calling the `useData` function outside of the `setData` function (say to populate the page after the user inputs a search term) you should first check that data exists, since a user could interact with the page before the data are returned resulting in an error or unexpected behavior.