JAVASCRIPT   92

localStorageAccess.js

Guest on 26th July 2021 04:32:31 PM

  1. export const setLocalStorage = function (variable, value, ttl_sec) {
  2.     var data = { value: value, expires_at: new Date().getTime() + (ttl_sec * 1000) / 1 };
  3.     localStorage.setItem(variable.toString(), JSON.stringify(data));
  4. };
  5.  
  6. export const getLocalStorage = function (variable) {
  7.     let data = null;
  8.     try {
  9.         data = JSON.parse(localStorage.getItem(variable.toString()));
  10.     } catch(e) {
  11.         return null;
  12.     }
  13.     if (data !== null) {
  14.         if (data.expires_at !== null && data.expires_at < new Date().getTime()) {
  15.             localStorage.removeItem(variable.toString());
  16.         } else {
  17.             return data.value;
  18.         }
  19.     }
  20.     return null;
  21. }

Raw Paste


Login or Register to edit or fork this paste. It's free.