Created
November 4, 2018 03:57
-
-
Save abachuk/ce85832bc843e97a62085cc99e3d8474 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// 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