Client Side Local Storage Caching in SharePoint

Hello Friends, in this article we will learn how to save SharePoint list data in local storage i.e. browser cache.

This code will save SharePoint list data in the local cache. It will check if the SharePoint list is updated. If the list is updated, it will invalidate the local storage cache (delete cache). Once the local cache is deleted, it will save the data again in the cache.

This is also called time-bound cache. We have used two functions as below:

1) getListLastModifiedDate : This function is used to get list last modified date.
2) readItem(): This function is used to get list data that we are going to save in local storage.

Save SharePoint List data in Browser Cache


Save SharePoint List data in Browser Cache

//Function to get list item last modified date time
//last modified date is used to Invalidate cache when backend list changes 
getListLastModifiedDate = function (siteUrl, listName) {
  var def = $.Deferred();
  $.ajax({
    url: siteUrl + "/_api/web/lists/GetByTitle('" + listName + "')/LastItemModifiedDate",
    type: 'GET',
    headers: {
      accept: "application/json;odata=verbose"
    },
    success: function (response) {
      def.resolve(response.value);
    },
    error: function (xhr, status, error) {
      def.reject('01/01/01');
      console.log(xhr.responseText + "\n" + error);
    }
  });
};

//Normal rest api function to get list data
readItem = function (siteUrl, listName) {
  var def = $.Deferred();
  $.ajax({
    url: siteUrl + "/_api/web/lists/getByTitle('" + listName + "')/Items(1)",
    type: 'GET',
    headers: {
      "accept": "application/json;odata=verbose",
    },
    success: function (data) {
      def.resolve(data.d);
    },
    error: function (xhr, status, error) {
      def.reject();
      console.log(xhr.responseText + "\n" + error);
    }
  });
}

Usage:

//Function to either get data from local storage or sharepoint based of cache invalidation/time bound cache
getListLastModifiedDate(_spPageContextInfo.webAbsoluteUrl, 'My_Events')
  .then(function (lastModifiedTime) {
    if (localStorage.getItem('Events') && localStorage.getItem('Events.expire')) {
      // get data from cache
      console.log(cache.get('Events'));
    }
    else {
      // get data from backend
      readItem().then(function (items) {
        console.log(items);
        localStorage.setItem("Events", JSON.stringify(items));
        localStorage.setItem("Events.expire", lastModifiedTime);
      });
    }
  });

Post a Comment

0 Comments