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

259
Visualizações
localStorage: Attempted to assign to readonly property

Wanting to learn Redux I started by trying to emulate the redux pattern in vanilla JavaScript. I used localStorage to centralize data.

Here's my GitHub repo -> https://github.com/GroovyHooked/Redux_Pattern

Everything seems to be working fine until I hit the refresh button. When I do, I am able to retrieve the stored data and log it in the console but if I hit a button to increase or decrease a value I get this error:

reducer.js:6 Uncaught TypeError: Cannot create property item on string {"item":5,"value":50}
    at reducer (reducer.js:6:18)
    at buyItem (action.js:6:3)
    at HTMLButtonElement.<anonymous> (index.js:15:41)

I'm a bit confused about what is going on and can't seem to find any info on the topic.

Can anyone, please, enlighten me on the subject?

/* --------- index.js ---------- */
import { buyItem, sellItem } from "./action.js";
import { BUY, SELL } from "./const.js";

export var store = localStorage.getItem("store") || { item: 0, value: 0 };

export const dataDisplay1 = document.querySelector("#state-item");
export const dataDisplay2 = document.querySelector("#state-value");

dataDisplay1.innerHTML = store.item ? store.item : 0;
dataDisplay2.innerHTML = store.value ? store.value : 0;

const button1 = document.querySelector("#buy");
const button2 = document.querySelector("#sell");

button1.addEventListener("click", () => buyItem({ type: BUY }));
button2.addEventListener("click", () => sellItem({ type: SELL }));

/* --------- action.js ---------- */
import { reducer } from "./reducer.js";
import { dataDisplay1, dataDisplay2 } from "./index.js";
import { store } from "./index.js";

export const buyItem = (action) => {
  reducer(store, action);
  dataDisplay1.innerHTML = store.item;
  dataDisplay2.innerHTML = store.value;
};

export const sellItem = (action) => {
  reducer(store, action);
  dataDisplay1.innerHTML = store.item;
  dataDisplay2.innerHTML = store.value;
};

/* --------- reducer.js ---------- */
import { BUY, SELL } from "./const.js";

export const reducer = (state, action) => {
  switch (action.type) {
    case BUY:
      state.item = state.item + 1;
      state.value = state.value + 10;
      return localStorage.setItem("store", JSON.stringify(state));

    case SELL:
      state.item = state.item - 1;
      state.value = state.value - 10;
      return localStorage.setItem("store", JSON.stringify(state));

    default:
      return localStorage.setItem(
        "store",
        JSON.stringify({ item: 0, value: 0, name: "Bankruptcy" })
      );
  }
};

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Seems like your issue is likely related to using JSON.stringified version of store then not JSON.parsing it before you try to assign to it.

/* --------- index.js ---------- */
import { buyItem, sellItem } from "./action.js";
import { BUY, SELL } from "./const.js";
const initialState = { item: 0, value: 0 };
export var store = JSON.parse(localStorage.getItem("store") || JSON.stringify(initialState));

export const dataDisplay1 = document.querySelector("#state-item");
export const dataDisplay2 = document.querySelector("#state-value");

dataDisplay1.innerHTML = store.item ? store.item : 0;
dataDisplay2.innerHTML = store.value ? store.value : 0;

const button1 = document.querySelector("#buy");
const button2 = document.querySelector("#sell");

button1.addEventListener("click", () => buyItem({ type: BUY }));
button2.addEventListener("click", () => sellItem({ type: SELL }));

/* --------- action.js ---------- */
import { reducer } from "./reducer.js";
import { dataDisplay1, dataDisplay2 } from "./index.js";
import { store } from "./index.js";

export const buyItem = (action) => {
  reducer(store, action);
  dataDisplay1.innerHTML = store.item;
  dataDisplay2.innerHTML = store.value;
};

export const sellItem = (action) => {
  reducer(store, action);
  dataDisplay1.innerHTML = store.item;
  dataDisplay2.innerHTML = store.value;
};

/* --------- reducer.js ---------- */
import { BUY, SELL } from "./const.js";

export const reducer = (state, action) => {
  switch (action.type) {
    case BUY:
      state.item = state.item + 1;
      state.value = state.value + 10;
      return localStorage.setItem("store", JSON.stringify(state));

    case SELL:
      state.item = state.item - 1;
      state.value = state.value - 10;
      return localStorage.setItem("store", JSON.stringify(state));

    default:
      return localStorage.setItem(
        "store",
        JSON.stringify({ item: 0, value: 0, name: "Bankruptcy" })
      );
  }
};

Also, keep in mind that you're probably better off /safer to reassign to the object rather than directly mutate it.

about 4 years ago · Juan Pablo Isaza Relatório
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