Skip to content

Instantly share code, notes, and snippets.

@KDCinfo
Last active September 10, 2020 15:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KDCinfo/f85143df6366c31ca0356ba5a15f3f27 to your computer and use it in GitHub Desktop.
Save KDCinfo/f85143df6366c31ca0356ba5a15f3f27 to your computer and use it in GitHub Desktop.
LocalStorage Functions with Testing Mock-up - `Typed` with TypeScript

LocalStorage Functions

... Typed with TypeScript
... With Testing Mock-up

In the Wild

GitHub - Done (for now) - Filename used: ./src/utilities/functions.ts

/*
Storage (local; client-side [window])
https://developer.mozilla.org/en-US/docs/Web/API/Storage
*/
/* STORAGE MOCKUP FOR TESTING (jsdom) */
if (typeof(window.localStorage) === 'undefined' || window.localStorage === null) {
// For Testing: Apparently you can disregard the TypeScript errors.
interface LocalStorageState {
[key: string]: string;
}
var localStorage = (function () {
let store: LocalStorageState;
return {
getItem: function (key: string) {
return store[key];
},
setItem: function (key: string, value: string) {
store[key] = value.toString();
},
clear: function () {
store = {};
},
removeItem: function (key: string) {
delete store[key];
}
};
})();
Object.defineProperty(window, 'localStorage', { value: localStorage });
}
/* STORAGE FUNCTIONS */
export const setStorageItem = (storage: Storage, key: string, value: string) => {
try {
storage.setItem(key, value);
} catch (e) {
// console.error(e)
}
};
export const getStorageItem = (storage: Storage, key: string) => {
try {
return storage.getItem(key);
} catch (e) {
// console.error(e)
return null;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment