2

I use the following to add values to local storage:

var thisId = "<?php echo $id; ?>";
localStorage.setItem("postId", thisId);
console.log(localStorage.getItem("postId"));

The following is loaded for each page i end up in, every time:

<?php echo $id; ?>

So it will become: 242 or 248 etc

Thing is each time I do console.log(localStorage.getItem("postId")); i only get one value as it is not adding as a list of values but replacing the old with the new one.

rob.m
  • 9,843
  • 19
  • 73
  • 162

6 Answers6

4

Use a list instead. As you can only store Strings into localStorage, the best approach is to use JSON parse/stringify methods to help you with data serialization.

  • Get the localstorage item as a list (JSON.parse)
  • Add the item
  • Save the list into localstorage (JSON.stringify)

var thisId = "1";//<?php echo $id; ?>

var localList = localStorage.getItem("postIdList") || "[]";
localList = JSON.parse(localList);

//Check repeated ID
var isExistingId = localList.indexOf(thisId) > -1;
if (!isExistingId) {
  localList.push(thisId);
}

localStorage.setItem("postIdList", JSON.stringify(localList));
console.log(localStorage.getItem("postIdList"));
  • could provide a code example instead of a conceptual logic? Saying this for future users too ending up on here – rob.m Mar 27 '18 at 10:57
  • thanks a lot for the code, it's a bit broken when I run the snippet but i get the idea, thank you – rob.m Mar 27 '18 at 11:04
1

Be sure to wait for all document components to be loaded, and after that you can insert your PHP value directly into the lcoalStorage. Be careful though, localStorage can ONLY contain simple variable, no objects or arrays. If you want to store an object or array, be sure to stringify it before saving it.

document.addEventListener('DOMContentLoaded', function(event){
    localStorage.setItem("postIdList", JSON.stringify ("<?=$idList?>") );
    console.log( JSON.parse ( localStorage.getItem("postIdList") ) );
});

EDIT. Here's an example of how to convert a PHP array to JSON and from there store it in the localStorage and convert it back to JSON.

<?php
$listIds = [1,2,5];
$jsonIds = json_encode( $listIds );
?>
<script>
    localStorage.setItem( "myIds", "<?=$jsonIds?>" );
    console.log( JSON.parse( localStorage.getItem( "myIds" ) ) );
</script>
BRO_THOM
  • 824
  • 9
  • 24
  • @RoryMcCrossan exactly – rob.m Mar 27 '18 at 10:58
  • @RoryMcCrossan with the exception that I actually explain OP can't store objects/arrays in localStorage. – BRO_THOM Mar 27 '18 at 11:00
  • 1
    Then it would help if you showed the OP the code to do that, as your current sample is just echoing their question. – Rory McCrossan Mar 27 '18 at 11:01
  • @RoryMcCrossan Edited. Also edited variables since they implied single values, not arrays or objects. – BRO_THOM Mar 27 '18 at 11:05
  • @rob.m why not just save the list under a single variable? Now you'll have to iterate through different key names to get the values. You COULD json_encode($list) and directly insert it into the localStorage. That would be much faster. – BRO_THOM Mar 28 '18 at 11:06
  • @BRO_THOM yeah that's actually a better logic, i'll try it out, thanks – rob.m Mar 28 '18 at 11:09
  • @rob.m if you want, I could expand my answer above to fit that example? – BRO_THOM Mar 28 '18 at 11:10
  • @BRO_THOM yes that'd be awesome – rob.m Mar 28 '18 at 11:10
  • 1
    @rob.m I've updated my answer. Check the second section for an example of how to convert PHP arrays to JSON and back to a Javascript array. – BRO_THOM Mar 28 '18 at 11:20
  • The array with the id list won't be generated form the same page, each time we end in a page, I am saving the id into the array, so adding to it. I need to use the unique function for the array tho as I could land on the same page and we wouldn't want to add the same id to the array if already present – rob.m Mar 28 '18 at 11:46
  • @rob.m you can simply use this example to get (JSON.parse) the current value, add an id using the `push` method, and after that set (JSON.stringify) it again. – BRO_THOM Mar 28 '18 at 11:49
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/167724/discussion-between-rob-m-and-bro-thom). – rob.m Mar 28 '18 at 11:50
0

setItem replace the string correspondent to that specific key if present. As suggested in the other answer fetch the current array of values update it and stringify it.

make sure to wrap the code in a try catch since json.parse could potentially raise an exception

try{
   let currentArray = Array.isArray(JSON.parse(localStorage.getItem("postId"))) 
     ? JSON.parse(localStorage.getItem("postId")) 
     : [];
   currentArray.push(thisId);
   localStorage.setItem("postId", JSON.stringify(currentArray));
}
catch(err){
   localStorage.setItem("postId", "[]");
}

https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage

Karim
  • 8,454
  • 3
  • 25
  • 33
0

Below is a really simple example that add random number to a list, you can just alter to suite your needs..

//first get current lines
var lines = localStorage.getItem("lines") ?
  JSON.parse(localStorage.getItem("lines")) : []; 

//lets add a random number to the list
lines.push(Math.random()); 
console.log(lines); 

//now lets save our new list
localStorage.setItem("lines", JSON.stringify(lines));
Keith
  • 22,005
  • 2
  • 27
  • 44
  • mmm what happens tho is that each time i load it will create a new array – rob.m Mar 27 '18 at 12:01
  • this is the final using your answer `var thisId = ""; var lines = localStorage.getItem("lines") ? JSON.parse(localStorage.getItem("lines")) : []; var myIdString = JSON.parse(localStorage.getItem("lines")); lines.push(thisId); function unique(list) { var result = []; $.each(list, function(i, e) { if ($.inArray(e, result) == -1) result.push(e); }); return result; } console.log(unique(lines));` – rob.m Mar 27 '18 at 12:55
  • not sure if I should accepting your answer tho, maybe I add to mine as yours is incomplete, as I did say a new id to the list when I load the page – rob.m Mar 27 '18 at 12:56
0

Working Fiddle

localStorage only supports strings so.

var id = [];// For sample
id[0] ="1";
id[1] ="2";
localStorage.setItem("ids", JSON.stringify(id));
var storedIds = JSON.parse(localStorage.getItem("ids"));
console.log(storedIds);
4b0
  • 21,981
  • 30
  • 95
  • 142
  • 1
    this is nice so basically `var thisId = ""; var id = []; id.push(thisId);` – rob.m Mar 27 '18 at 11:30
  • Yap Happy coding :) – 4b0 Mar 27 '18 at 11:32
  • mmm what happens tho is that each time i load it will create a new array – rob.m Mar 27 '18 at 11:33
  • According to this old answer https://stackoverflow.com/questions/2989284/what-is-the-max-size-of-localstorage-values local storage have some limits so try to reuse array rather than create new every time or remove old one and create new one. – 4b0 Mar 27 '18 at 11:38
0

Probably not the most beautiful and it'd become very long if more than two are needed, but this is A solution.

So basically i create two localStorage and I first check if they are empty and if the key isn't the same as per the variable I am setting, and do this each time I load the page.

if(!localStorage.getItem("idA")) {
  var thisId = "<?php echo $id; ?>";
  localStorage.setItem("idA", thisId);
  console.log("A " + localStorage.getItem("idA"));
} else {
  console.log("A " + localStorage.getItem("idA"));  
}
if(localStorage.getItem("idA") != "<?php echo $id; ?>") {
  if(!localStorage.getItem("idB")) {
    var thisId = "<?php echo $id; ?>";
    localStorage.setItem("idB", thisId);
    console.log("B " + localStorage.getItem("idB"));
  } else {
    console.log("A " + localStorage.getItem("idA"));  
    console.log("B " + localStorage.getItem("idB"));
  }
}

UPDATE

Based on Keith Answer, to add unique values (see this reply on SO), this is what I did:

var thisId = "<?php echo $id; ?>"; 
var lines = localStorage.getItem("lines") ? JSON.parse(localStorage.getItem("lines")) : []; 
var myIdString = JSON.parse(localStorage.getItem("lines")); 
lines.push(thisId); 
function unique(list) { var result = []; 
$.each(list, function(i, e) { 
  if ($.inArray(e, result) == -1) result.push(e); }); 
  return result; 
} 
console.log(unique(lines));
rob.m
  • 9,843
  • 19
  • 73
  • 162
  • In what way is this a better approach than just using the 1 localeStorage slot, and JSON.stringify / parse, like everybody else mentioned?.. This approach seems very inflexible, and gains you nothing compared to 1 localeStorage item.. – Keith Mar 27 '18 at 12:31
  • it is not flexible indeed and it is NOT absolutely the best solution. What happen is that `var thisId = "";` is a new ID set on each page load, i understand the jSon string trick, however, each time I load the page, the values are added, so the other answers would replace the values on each page load, not adding to it – rob.m Mar 27 '18 at 12:34
  • @Keith see your `JSON.parse(localStorage.getItem("lines")) : [];` is created each time we page load – rob.m Mar 27 '18 at 12:36
  • It's created if it doesn't exist, otherwise it loads it from localStorage. If you ran the code of mine inside say Chromes console, every time you run it a random number is added to the list,.. Refresh the browser, and the list will continue from were it left off etc. Is this not what your after? – Keith Mar 27 '18 at 12:39
  • let me try it, might work, haven't actually tried yours. I was also thinking of using `contains` and add the new `string` (thanks to the `JSON.stringify / parse` trick) if is not there – rob.m Mar 27 '18 at 12:41
  • i confirm, each time i reload the same page, using your bit, i get the old value added again, resulting in duplicated values `(2) ["248", "248"]`, probably I could use `contains`, will try it now – rob.m Mar 27 '18 at 12:44
  • Yes, I did say if you alter to fit your needs, if you want unique id's adding to the list, it's the same approach. btw. it's `includes`, not `contains`.. eg. `JSON.parse('["one", "two"]').includes("two")` etc. – Keith Mar 27 '18 at 12:45
  • @Keith ok i made it work using your answer but I had to use array unique, following this https://stackoverflow.com/a/12551709/1018804 then this `console.log(unique(lines));` – rob.m Mar 27 '18 at 12:54
  • JSON.parse could potentially raise an exception (either if the key is not defined or if the user change the value) , i'd suggest wrapping the code in a try catch block, and if any error is raise initialize the key to an empty array. https://stackoverflow.com/questions/49511011/how-to-add-values-as-a-list-in-localstorage/49512756#answer-49511284 – Karim Mar 27 '18 at 14:35