function fetchAndCacheIp() {
  fetch("https://api.ipify.org?format=json")
    .then(response => response.json())
    .then(data => {
      const { ip } = data;
      // Store the IP in LocalStorage for later use
      localStorage.setItem("cachedIp", ip);
      localStorage.setItem("lastCachedTime", new Date().getTime());
    })
    .catch(error => {
      console.error(error);
    });
}

let cachedIp = localStorage.getItem("cachedIp");
let lastCachedTime = localStorage.getItem("lastCachedTime");
const cacheExpiryInMins = 120; // cache expiry in minutes

if (
  !cachedIp ||
  !lastCachedTime ||
  new Date().getTime() - lastCachedTime > cacheExpiryInMins * 60 * 1000
) {
  fetchAndCacheIp();
}