Last active
July 2, 2018 20:44
-
-
Save reecelucas/87dd767fa6e041a7b6b5054fd8860149 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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); | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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