Instantly share code, notes, and snippets.

Embed
What would you like to do?
// let's define our expiration date
const today = new Date();
let expDate = new Date();
expDate.setDate(today.getDate() + 30); // 30 days expiration
// a searches user does in your app on the first visit, we collect them to save to localStorage
const userRecentlocations = [
{ city: "New York", country: "US", id: "2390230" },
{ city: "Athens", country: "GR", id: "304802" },
{ city: "Kyiv", country: "UA", id: "1239488" }
];
// if localStorage is available, we'll save user's serach history under recentSearches key
if (typeof (Storage)) {
// we can add as much extra data as we want, in our case we are adding expiration
localStorage.setItem("recentSearches", JSON.stringify({
expiration: expDate,
locations: userRecentlocations
}));
}
/** 🦄 **/
// bunch of your app logic
/** 🔥 **/
// when it's time to access previous search history, first we check if we can
if (typeof (Storage)) {
const recentSearches = JSON.parse(localStorage.getItem("recentSearches"));
// then check for expiraiton date before showing to the user
if(new Date(recentSearches.expiration) > new Date()) {
console.log(recentSearches.locations)
} else {
// we can completely clear the value OR display user friendly massage
console.log("Unfortuenately your search history has expired");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment