0

i need help!

I am looking to uses chrome local storage in one of my apps. Basically this is supposed to be a shopping list app that store locally previously entered items as an object in JavaScript.

i must be doing something wrong because when there is nothing in local storage and i add an item i gets saved fine but then whenever i add a second item, the previous item gets replaced.

Here's my code so far

function useLocalStorage(shoppingListItem){

    let shoppingApp = {};
    
    if (localStorage.getItem(shoppingApp) === null){
       shoppingApp.shoppingList = [];
    }
    else {
       shoppingApp.shoppingList = JSON.parse(localStorage.getItem('shoppingApp.shoppingList'));
    }

    shoppingApp.shoppingList.push({
      shoppingListItem : shoppingListItem,
      checked : false,
    });

    localStorage.setItem(shoppingApp.shoppingList.shoppingListItem, 
                         JSON.stringify(shoppingApp.shoppingList));
}
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Manara
  • 21
  • 3
  • adding shopping list to storage is bad practice. use session – Abdulla Nilam Dec 08 '20 at 12:30
  • Are `shoppinApp`, `shoppingApp` and `'shoppingApp.shoppingList'` meant to be equal or different? – Álvaro González Dec 08 '20 at 12:33
  • sorry for the typo, i fixed it. shoppingApp is the containing object, shoppingList is a list property of that object and shoppingListItem is an item (object) in my shopping list – Manara Dec 08 '20 at 13:08
  • Keys must be strings, just like values. So the value passed to `getItem`, and the first argument to `setItem`, must be a string – Heretic Monkey Dec 08 '20 at 13:32
  • Does this answer your question? [Storing Objects in HTML5 localStorage](https://stackoverflow.com/questions/2010892/storing-objects-in-html5-localstorage) – Heretic Monkey Dec 08 '20 at 13:34

1 Answers1

0

Did you see how your localStorage looks like after executing the function?

If you did not do typos in code:

localStorage.setItem(
    shoppingApp.shoppingList.shoppingListItem, 
    JSON.stringify(shoppingApp.shoppingList)
);

The first argument will return undefined, you are trying to access proprty of shoppingListItem on shoppingList which is array. To get any value you need to access the item directly with for example shoppingApp.shoppingList[0]. Because of this error(?) for me it saves the list in undefined key.

let shoppingApp = {};

if (localStorage.getItem(shoppingApp) === null){
    shoppingApp.shoppingList = [];
}

This if statement is always true. What you are doing is trying to access item with key {} and because there is no key like that in your localStorage it returns null so your new shopping list is empty. You probably wanted to use here string: if (localStorage.getItem('shoppingApp') === null). If you were to write the {} as a key so you could access it later - it would get parsed and the key would be "[object Object]" so I do not think that is your intended behaviour.

michalbargiel
  • 321
  • 1
  • 3