r/learnjavascript • u/kaatarina_zed_talon • Oct 28 '26
Using the session storage was a lot of pain
async function isThereProductsInDb(): Promise<boolean> {
const url = '/Admin/IsThereProductsInDb';
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Response status: ${response.status}`);
}
const isThereProductsInDb = await response.json();
return isThereProductsInDb;
} catch (error: any) {
console.error(error);
return false;
}
}
async function Main() {
var thereAreProductsInDb = await isThereProductsInDb();
// Source - https://stackoverflow.com/a/50269969
// Posted by Ted
// Retrieved 2026-10-26, License - CC BY-SA 4.0
if (!thereAreProductsInDb) {
console.log("There are no products in the database.");
const productsContainer = document.getElementById("products-container");
productsContainer!.innerHTML = '';
var notification = document.createElement("p");
notification.innerText = "There are no products in the database yet,please import products in order to show them here."
notification.className = "alert alert-info text-center mx-auto col-12 col-md-8 col-lg-6 p-3 p-md-4";
notification.id='noProductsAvailableNotification'
notification.setAttribute("role", "alert");
productsContainer!.appendChild(notification);
sessionStorage.setItem("hideShowProductsAnchor", "true");
document.getElementById("showProductsAnchor")!.hidden = true;
return
}
document.getElementById("noProductsAvailableNotification")!.innerText = "click the button to show the products";
sessionStorage.setItem("hideShowProductsAnchor", "false");
document.getElementById("showProductsAnchor")!.hidden = false;
console.log("There are products in the database!");
}
console.log("`isThereProductsInDb` script was executed");
/**Period checking, otherwise the browser will not be aware of manual products deletion using SSMS*/
/**
*
* Note : SSMS is an abbreviation for Sql Server management studio.
*/
let isRunning = false;
setInterval(async () => {
if (isRunning) return;
isRunning = true;
try {
await Main();
} finally {
isRunning = false;
}
}, 1000);the session storage was used so that if there is no products in the database, then there is no need to show the anchor element that enables the user to view the products, because there are no products in the first place, otherwise the anchor element must be shown.
he reason the session storage was used in the first place is that when the anchor element is clicked, it should be hidden because when the shown products are paginated, so there is no need to show that anchor element anymore, to hide the anchor, the hidden property is used . Due to the fact that the page reloads after the anchor is clicked and that I should not use e.preventDefault() because that will prevent the request from reaching the server, the state of the hidden property is lost, so it must be preserved some where, so I decided to use session storage like this :
// Source - https://stackoverflow.com/a/11550299
// Posted by Jason Hazel
// Retrieved 2026-10-27, License - CC BY-SA 3.0
window.addEventListener("load", (event) => {
sessionStorage.setItem("hideShowProductsAnchor", "false");
});
const productsPageNavigators: NodeList = document.querySelectorAll("a.productsPageNavigator");
const showProductsAnchor = document.getElementById("showProductsAnchor")
productsPageNavigators.forEach((navigator) => {
navigator.addEventListener("click", function (e) {
sessionStorage.setItem("hideShowProductsAnchor", "true");
}, false);
});
// Restore the hidden state after the page reloads
if (sessionStorage.getItem("hideShowProductsAnchor") === "true") {
showProductsAnchor!.hidden = true;
}
else {
showProductsAnchor!.hidden = false;
}Managing the session storage is painful; are there any other alternatives that are easier to maintain ?
1
u/Best_Addition6297 Oct 28 '26
drop sessionStorage entirely. Call your async function on DOMContentLoaded to set the hidden attribute directly based on the fresh server response
1
u/realmauer01 Oct 28 '26
I made a redis like repository for session and local storage. That being said, you very likely dont need to use any kind of storage at all here.
0
u/Awayes-Rheanon Oct 28 '26
is the server rendering the HTML on that reload, or is it just static files? If your backend is generating the page when they click the link, it already knows whether products exist and which page youre on, so it can just render the anchor with the `hidden` attribute directly.
-1
u/koraynar Oct 28 '26 •
Yes—you can remove sessionStorage from this flow. Whether the link is visible is derived from the latest successful server response; storing a second hide/show flag just gives you another value to keep in sync.
Create the notification element once in your HTML, outside the products container if you clear that container. After the DOM is ready, get references to it and the anchor and check that both exist. Put the UI updates in one function: for a confirmed boolean hasProducts, set anchor.hidden = !hasProducts and update the message accordingly.
There are two separate issues in the snippet worth fixing first:
- If the page starts with products, the true branch accesses noProductsAvailableNotification even though only the empty branch creates it. TypeScript's ! doesn't create the element or prevent a null error at runtime.
- The catch returns false for network/HTTP/JSON errors, so a failed check clears the displayed products as if the database were empty. Keep failure separate: show 'Unable to check' and preserve the last successful view.
Your isRunning guard already prevents overlapping checks. Test initial empty, initial populated, empty-to-populated, populated-to-empty, and a failed request. I'd make those work before changing the polling mechanism.
-4
u/azhder Oct 28 '26