Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

437
Views
JavaScript localStorage not updating across multiple files

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 :)

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!