简体   繁体   中英

localStorage.setItem not working for toggleButton

I am toggling between a graph and a table view of data. I am using localstorage to save the state. From my console, I can see that dataViewType is not set or saved in my localstorage. I am using vanilla JavaScript, what am I getting wrong or missing?

Update: I can set dataViewType now, but how can I get it/preserve the state on refresh? Code reflects new changes.

    const toggleData = () => {
    const data = document.querySelectorAll("button.data");
    const dataTable = document.querySelector(".dataTable");
    const dataGraph = document.querySelector(".dataGraph");
    let dataType = localStorage.getItem("dataViewType");
    if (dataType = "block") {
        if (dataTable.style.display === "block") {
            dataTable.style.display = "none";
            dataGraph.style.display = "block";
            data.forEach(
                (element) => (element.innerText = "View data as Table"),
                localStorage.setItem("dataViewType", "block")

            );
        } else {
            dataGraph.style.display = "none";
            dataTable.style.display = "block";
            data.forEach(
                (element) => (element.innerText = "View data as Graph"),
                localStorage.setItem("dataViewType", "none")
            );
        }
    }
};
    window.addEventListener("DOMContentLoaded", (event) => {
    
        const data = document.querySelectorAll("button.data");
        data.forEach((element) =>
            element.addEventListener("click", (event) => ToggleData()),
        );
    }

The logic in your toggle routine is wrong. First of all neither of the functions will be executed unless there is somethign already stored under dataViewType in localstorage and if there is something stored, the same function will be executed over and over again, because it sets the same value that triggers that function execution...

So what you need need is remove if (dataType) { and switch places of other conditions:

const Toggledata = () => {
    const dataType = localStorage.getItem("dataViewType");

        if (dataType === "Graph") {
            ViewdataTable();

        } else if (dataType === "Table") {
            ViewdataGraph();

        }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM