Kelvin Mitaki
Kelvin Mitaki

Reputation: 98

local storage with redux not working as expected

I am a beginner in JavaScript and I am working on an E-commerse test application with React and Redux where I need to persist data on the cart (I am using local storage for that). As I add items to the cart, they are stored in local storage, when I refresh the page data is still persisted in the local storage. The problem comes when I try adding other items to the cart after page refresh, instead of adding to the items that were initially there, it starts adding from zero.

here is a code snippet for that:

MY REDUX ACTION

const arr = [];
export const addItem = (itemsAddedToCart) => {
  const id = Math.random();
  arr.push({ ...itemsAddedToCart, id: id });
  const test = JSON.stringify(arr);
  localStorage.setItem("test", test);
  return {
    type: "ADD_ITEM",
    payload: { ...itemsAddedToCart, id: id },
  };
};

P.S. Sorry for my bad English

Upvotes: 1

Views: 954

Answers (1)

user54321
user54321

Reputation: 632

Looks like localStorage.setItem() overwrites what's already in the local storage.
To update what's in the local storage without removing the old entries, you can read local storage content first, merge the new items and write to storage.

const arr = [];
export const addItem = (itemsAddedToCart) => {
  const id = Math.random();

  arr.push({ ...itemsAddedToCart, id: id });
  //get the new elements' ids to a set
  const ids = new Set(arr.map(d => d.id));


  //read stored items from storage and join them to arr
  const storedItems = localStorage.getItem("test");
  if(storedItems) {
    const storedItemsParsed = JSON.parse(storedItems);
    // if the item is not in new items, add them to arr
    arr = [..arr, ...storedItemsParsed.filter(item=> !ids.has(item.id)) ]
  }


  const test = JSON.stringify(arr);
  localStorage.setItem("test", test);
  return {
    type: "ADD_ITEM",
    payload: { ...itemsAddedToCart, id: id },
  };
};

Upvotes: 1

Related Questions