I am trying to toggle between a table and a graph. I have written a couple of functions save the state that the user switches to using localstorage. But when I console.log localStorage.getItem, i see the value as null. What am I missing? This is Vanilla Javascript
const data = document.querySelectorAll("button.data");
const dataTable = document.querySelector(".dataTable");
const dataGraph = document.querySelector(".dataGraph");
const ViewdataGraph = () => {
dataTable.style.display = "none";
dataGraph.style.display = "block";
data.forEach(
(element) => (element.innerText = "View data Table"));
localStorage.setItem("dataViewType", "Graph");
}
const ViewdataTable = () => {
dataGraph.style.display = "none";
dataTable.style.display = "block";
data.forEach(
(element) => (element.innerText = "View data Graph"));
localStorage.setItem("dataViewType", "table");
}
const Toggledata = () => {
const dataType = localStorage.getItem("dataViewType");
if (dataType) {
if (dataType === "table") {
ViewdataTable();
} else if (dataType === "Graph") {
ViewdataGraph();
}
}
};
window.addEventListener("DOMContentLoaded", (event) => {
const data = document.querySelectorAll("button.data");
data.forEach((element) =>
element.addEventListener("click", (event) => ToggleData()),
);
}
CodePudding user response:
on your code only I see that you have 2 dots on this line of code localStorage..setItem("dataViewType", "table");
change to this localStorage.setItem("dataViewType", "table");
I hope this is your problem
CodePudding user response:
You have a typo in your ViewdataTable
function.
localStorage.setItem("dataViewType", "table");
Also, there's a problem in Toggledata
, when localStorage has no dataViewType
item, the variable dataType
will be null
, hence no changes will be made to your view or localStorage
. I suggest using an array of views and storing the index of the active view.
const views = [
{ elem: dataTable, name: 'Table' },
{ elem: dataGraph, name: 'Graph' },
];
let viewIndex = -1;
const Toggledata = () => {
views[viewIndex].elem.style.display = "none";
viewIndex ;
// wrapping
if (viewIndex >= views.length) {
viewIndex = 0;
}
const view = views[viewIndex];
view.elem.style.display = "block";
data.forEach(element => (element.innerText = `View data ${view.name}`));
localStorage.setItem("dataViewType", String(viewIndex));
};
window.addEventListener("DOMContentLoaded", (event) => {
const data = document.querySelectorAll("button.data");
data.forEach((element) =>
element.addEventListener("click", (event) => ToggleData()),
);
// use first view if dataViewType is not set
viewIndex = Number(localStorage.getItem("dataViewType") || "0");
// not a valid value
if (Number.isNaN(viewIndex) || !(viewIndex in views)) {
viewIndex = 0;
}
// maybe not necessary if HTML style sets display to none by default
views.forEach(v => (v.elem.style.display = 'none'));
views[viewIndex].elem.style.display = 'block';
}