Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

428
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda