0

I've been trying to do this all day and just can't get it right. I've read many articles on various websites and tried many different approaches, but I am still getting issues of one kind or another.

Sorry if it's a little haphazard, I'm struggling to see my issue and so I'm struggling on what area to ask for help.

Component aim: Array stored on LS that holds objects, that hold information on shows Component issue: Depending on the code I seem to either be overwritting a single object, cant log more than 2 objects (that then overwrite each other) or after storing 1 object fine the array starts messing up with more entries.

TLDR:

All I'm trying to do at this point is:

-push new object onto new showList array

-pull my objects from a showList array in LS (if exists), push into new showList

-stringify, then push my new combine array into LS

Below is the relative function.

function addNewShow(titleArg, typeArg, genreArg, watchedArg) {
  var showList = [];

  var show = {
    title: titleArg,
    type: typeArg,
    genre: genreArg,
    watched: watchedArg
  };
  showList.push(show);
  showList.push(JSON.parse(localStorage.getItem('showList')));
  console.log(showList);


  localStorage.setItem("showList", JSON.stringify(showList));
};

If you'd prefer to see the project you can see that here: https://codepen.io/11PH/pen/NONJBa?editors=1011

Any help much appreciated, thank you in advance.

3 Answers 3

5

You are pushing entire array received from local storage into second position of local showList array, you should use array concatenation:

localStorage.removeItem('showList');

function addNewShow(titleArg, typeArg, genreArg, watchedArg) {
  var showList = [];

  var show = {
    title: titleArg,
    type: typeArg,
    genre: genreArg,
    watched: watchedArg
  };
  showList.push(show);
  showList = showList.concat(JSON.parse(localStorage.getItem('showList')||'[]'));
  console.log(showList);


  localStorage.setItem("showList", JSON.stringify(showList));
};

addNewShow(1,2,3,4);
addNewShow(1,2,3,5);
addNewShow(1,2,3,6);
addNewShow(1,2,3,7);

Little snippet showing why (jsonString||"[]") is important:

var array = [1,2,3,4];
console.log("array is:");
console.log("\t",  array ); 
console.log("concating null adds new null element to the array");
console.log("\t",  array.concat(null) ); 
console.log("concating empty array deosn't change anything");
console.log("\t",  array.concat([]) );
console.log("result of expresion (null||[]) is empty array not null");
console.log("\t", null||[]);
console.log("puting it all together, if we don't want to add null to the array then we can write   array.concat( null||[] )");
console.log("\t",  array.concat( null||[] ) ); 

console.log('additionaly JSON.parse(null) in null');
console.log("\t",  JSON.parse(null) ); 

Array.concat just works that way - MDN is great source of documentation and examples - here for concat.

Sign up to request clarification or add additional context in comments.

5 Comments

I had tried concatenating, must have messed it up somewhere. Could you explain a bit about the ' || '[]' " you wrote? I thought it was to create the array to store within but that's done further up with var showList = [];
localStorage.getItem('showList')||'[]') is to get array when value of showList item in local storage is null. If it's null then we run JSON.parse on string "[]" - that return empty table and guarantees that parameter passed to showList.concat( parameter ) is always the array.
Why would it ever be null though, before any entries have been made? Is it just a safety net?
It would be null before initialization on item in localStorage(run localStorage.getItem('asdjbsdfhbj') and check result), if i haven't change null to empty array concat would add null as last element to array. I'm adding snippet to answer to illustrate it, wait a moment.
This is all really helpful thank you, the example is great. A bit I still struggle to understand is why does concat add null? If I'm going round in circles I'll look into concat so more I guess.
3

You should read showList from localStorage first, then push show onto that array.

function addNewShow(titleArg, typeArg, genreArg, watchedArg) {
  // Get array from local storage, defaulting to empty array if it's not yet set
  var showList = JSON.parse(localStorage.getItem('showList') || "[]");

  var show = {
    title: titleArg,
    type: typeArg,
    genre: genreArg,
    watched: watchedArg
  };
  showList.push(show);
  localStorage.setItem("showList", JSON.stringify(showList));
};

2 Comments

Hey, thanks that seems like a clean fix thanks, I guess I had things in thew wrong order. This helps explain the ` || "[]" `a bit also. Is it implemented for the first entry? As there wouldn't be an array before any entries.
Right. When there's no LS item yet, getItem returns null, so we use "[]" as the default.
0

first check for localstorage, then you can use spread operator for iteration

  function addNewShow(titleArg, typeArg, genreArg, watchedArg) {
  var showList = [];

  var show = {
    title: titleArg,
    type: typeArg,
    genre: genreArg,
    watched: watchedArg
  };
  showList.push(show);
  var finalArr = localStorage.getItem('showList') != undefined ? [...showList, ...JSON.parse(localStorage.getItem('showList'))] : showList;
  localStorage.setItem("showList", JSON.stringify(finalArr));
};

1 Comment

Your function won't work when invoked for first time. It will set showList to ""(string containing serialization of empty string) instead of array of length 1 with element from local variable show.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.