I'm wanting to store an integer in localStorage and be able to use it over multiple JavaScript files. However, the other files are referencing an old value even after I've set it to a new one.
Here is a condensed version of the JSON file I'm working with:
export const data = [
{
"username": "steve"
},
{
"username": "fred"
}
Here is the code where I'm setting the value of the localStorage key:
import { renderMenu } from "./menuPage.js";
import { data } from "../data/data.js"; // JSON file containing data
const usernameInput = document.createElement("input");
const btn = document.createElement("btn");
btn.addEventListener("click", (ev) => {
var username = usernameInput.value;
const user = data.find(u => (u.username === username));
if (!user) {
errText.textContent = "Incorrect username";
} else {
var dataIndex = data.indexOf(user);
console.log(dataIndex);
if (localStorage.getItem("dataIndexLocalStorage") !== dataIndex) {
localStorage.setItem("dataIndexLocalStorage", JSON.stringify(dataIndex));
}
renderMenu();
}
}
For example, if the username I entered was "steve", I expect console.log(dataIndex);
to output 0
.
Here is the code where I'm getting the value of the localStorage key (this code is used on multiple JavaScript files):
import { data } from "../data/data.js";
const dataIndex = parseInt(localStorage.getItem("dataIndexLocalStorage"));
export function renderMenu() {
console.log(dataIndex);
}
Following the example stated before, I still expect console.log(dataIndex);
to output 0
. It does this in some cases (sometimes it just outputs null
).
In the cases where it does indeed output 0
, if I was to enter "fred" as the username, I expect console.log(dataIndex);
to output 1
. However, in the renderMenu() function, console.log(dataIndex);
still outputs 0
, not 1
as it does so in the main code.
Am I missing something really basic? It seems strange that it doesn't update the value everywhere.
I appreciate any help I can get :)
I'm answering this question now just incase other people come across it:
I just had to put dataIndex = parseInt(...) into the renderMenu function, and declare var dataIndex as a global variable at the top of the file:
import { data } from "../data/data.js";
var dataIndex;
export function renderMenu() {
dataIndex = parseInt(localStorage.getItem("dataIndexLocalStorage"));
console.log(dataIndex);
}