r/learnjavascript • • 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 Upvotes

10 comments sorted by

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 • Bravo

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.

-1

u/kaatarina_zed_talon Oct 28 '26

Can you see the edits ? thanks for your time.

-1

u/koraynar Oct 28 '26 • Bravo

Yes, I can see the pagination explanation now—that changes my earlier assumption. There are two separate facts: “products exist” and “this page is already showing the product list”. The link should depend on both, not just the database check.

Because you're doing normal server navigation, the simplest option is to have the server-rendered page decide whether it needs the “show products” link. If the response already contains the paginated list, don't render that link (or render it hidden). Let the anchor navigate normally; you don't need preventDefault() for that approach.

In the added snippet, the load handler resets your stored flag to false on every page load, undoing the state you're trying to preserve. Independently, Main() unhides the link every successful poll when products exist, so it can override your pagination state again.

If you keep sessionStorage temporarily, don't reset it unconditionally on load, and don't let the polling function overwrite the “list already shown” state. Test reload and page 1 → page 2 with products present; the link should stay hidden on both list pages.

-4

u/azhder Oct 28 '26
  1. That is a lot of code we didn't have to see.
  2. That is a TypeScript code, not JavaScript code
  3. You are not discussing a JavaScript, but a Web technology. A lot of those Web technologies, like the DOM that come from the browser are crude and hard to work with because they are primarily made like their entire code base, like looking at a C++ API surface
  4. There are alternative to session storage if your use case is allowing for them and there aren't alternatives to session storage if your use case doesn't allow for them, so you could try asking in a web oriented sub, like r/webdev, not one for learning JavaScript
  5. This is an important one: remember me saying they look like a C++ API surface? Well, don't expect the alternatives to be as easy to work with as session storage. Usually the local/session storage is considered the simpler solution for simpler use cases.

0

u/kaatarina_zed_talon Oct 28 '26

Thanks for the notes. I will take them —especially the first one— into consideration.