Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

426
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda