Skip to content

Instantly share code, notes, and snippets.

@reecelucas
Last active July 2, 2018 20:44
Show Gist options
  • Save reecelucas/87dd767fa6e041a7b6b5054fd8860149 to your computer and use it in GitHub Desktop.
Save reecelucas/87dd767fa6e041a7b6b5054fd8860149 to your computer and use it in GitHub Desktop.
/**
* @param {String} key
* @param {Any} value
* @param {Number} expirationDays
* @returns {void}
*/
export const saveToLocalStorage = ({ key, value, expirationDays }) => {
// Try for localStorage support...
try {
// Convert days to milliseconds (ms)
const expirationMS = expirationDays * 24 * 60 * 60 * 1000;
const record = {
value: JSON.stringify(value),
timestamp: new Date().getTime() + expirationMS
};
localStorage.setItem(key, JSON.stringify(record));
} catch (error) {
console.warn(error);
}
};
/**
* @param {String} key
* @returns {(Object|void)}
*/
export const fetchFromLocalStorage = key => {
// Try for localStorage support...
try {
const record = JSON.parse(localStorage.getItem(key));
// Return the record if it exists & its timestamp has not expired
if (record && new Date().getTime() < record.timestamp) {
return JSON.parse(record.value);
}
} catch (error) {
console.warn(error);
}
};
import { saveToLocalStorage } from 'local-storage';
saveToLocalStorage({
key: 'name',
value: 'Reece Lucas',
expirationDays: 7
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment