rob.m
rob.m

Reputation: 10571

How to add values as a list in localStorage?

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.

Upvotes: 2

Views: 1412

Answers (6)

BRO_THOM
BRO_THOM

Reputation: 851

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>

Upvotes: 1

Karim
Karim

Reputation: 8632

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

Upvotes: 0

rob.m
rob.m

Reputation: 10571

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));

Upvotes: 0

4b0
4b0

Reputation: 22323

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);

Upvotes: 0

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"));

Upvotes: 4

Keith
Keith

Reputation: 24191

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));

Upvotes: 0

Related Questions